search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript object-oriented examples

Detailed explanation of JavaScript object-oriented examples

Feb 12, 2018 am 09:47 AM
javascriptjsDetailed explanation

Constructor and prototype object

Constructor is also a function. It is a function called when creating an object with new. One difference from ordinary functions is that its first letter should be capitalized. But if the constructor is called as an ordinary function (missing the new keyword), you should pay attention to the problem pointed by this. This article mainly introduces the essence of JavaScript object-oriented to you, and I hope it can help you.


var name = "Pomy";
function Per(){
  console.log("Hello "+this.name);
}
var per1 = new Per(); //"Hello undefined"
var per2 = Per();  //"Hello Pomy"

When using new, this object will be automatically created. Its type is the constructor type and points to the object instance; without the new keyword, this points to the global object.

You can use instanceof to detect the object type. At the same time, each object automatically has a constructor attribute when it is created, pointing to its constructor (object created in literal form or Object constructor, pointing to Object, custom constructor The object created by the function points to its constructor).


console.log(per1 instanceof Per); //true
console.log(per1.constructor === Per); //true

Each object instance has an internal property: [[Prototype]], which points to the prototype object of the object. The constructor itself also has a prototype attribute pointing to the prototype object. All created objects share the properties and methods of this prototype object.


function Person(){}
Person.prototype.name="dwqs";
Person.prototype.age=20;
Person.prototype.sayName=function()
{
  alert(this.name);
};
var per1 = new Person();
per1.sayName(); //dwqs
var per2 = new Person();
per2.sayName(); //dwqs
alert(per1.sayName == per2.sayName); //true

So, the pointer in the instance only points to the prototype, not the constructor. ES5 provides hasOwnProperty() and isPropertyOf() methods to reflect the relationship between prototype objects and instances


alert(Person.prototype.isPrototypeOf(per2)); //true
per1.blog = "www.ido321.com";
alert(per1.hasOwnProperty("blog")); //true
alert(Person.prototype.hasOwnProperty("blog")); //false
alert(per1.hasOwnProperty("name")); //false
alert(Person.prototype.hasOwnProperty("name")); //true

Because the constructor property of the prototype object points to the constructor itself, so When rewriting the prototype, you need to pay attention to the pointing problem of the constructor attribute.


function Hello(name){
  this.name = name;
}
//重写原型
Hello.prototype = {
  sayHi:function(){
    console.log(this.name);
  }
};
var hi = new Hello("Pomy");
console.log(hi instanceof Hello); //true
console.log(hi.constructor === Hello); //false
console.log(hi.constructor === Object); //true

Using object literal form to rewrite the prototype object changes the properties of the constructor, so the constructor points to Object instead of Hello. If the constructor pointer is important, you need to manually reset its constructor attribute when rewriting the prototype object


Hello.prototype = {
  constructor:Hello,
  sayHi:function(){
    console.log(this.name);
  }
};
console.log(hi.constructor === Hello); //true
console.log(hi.constructor === Object); //false

Using the characteristics of the prototype object, we can easily set it in JavaScript Add a custom method to the prototype object:


Array.prototype.sum=function(){
  return this.reduce(function(prev,cur){
    return prev+cur;
  });
};
var num = [1,2,3,4,5,6];
var res = num.sum();
console.log(res); //21
String.prototype.capit = function(){
  return this.charAt(0).toUpperCase()+this.substring(1);
};
var msg = "hello world";
console.log(msg.capit()); //"Hello World"

Inheritance

Using the [[Prototype]] feature, prototype inheritance can be achieved ; For objects in literal form, Object.prototype will be implicitly specified as [[Prototype]], or it can be specified explicitly through Object.create(), which accepts two parameters: the first one is pointed to by [[Prototype]] object (prototype object), the second is an optional property descriptor object.


var book = {
  title:"这是书名";
};
//和下面的方式一样
var book = Object.create(Object.prototype,{
  title:{
    configurable:true,
    enumerable:true,
    value:"这是书名",
    wratable:true
  }
});

Literal objects will inherit from Object by default. A more interesting usage is to implement inheritance between custom objects.


var book1 = {
  title:"JS高级程序设计",
  getTitle:function(){
    console.log(this.title);
  }
};
var book2 = Object.create(book1,{
  title:{
    configurable:true,
    enumerable:true,
    value:"JS权威指南",
    wratable:true
  }
});
book1.getTitle(); //"JS高级程序设计"
book2.getTitle(); //"JS权威指南"
console.log(book1.hasOwnProperty("getTitle")); //true
console.log(book1.isPrototypeOf("book2")); //false
console.log(book2.hasOwnProperty("getTitle")); //false

When accessing the getTitle attribute of book2, the JavaScript engine will perform a search process: now search for the own attributes of book2, and use it if found. If not found, then Search [[Prototype]], if not found, continue to search [[Prototype]] of the prototype object until the end of the inheritance chain. The end is usually Object.prototype, with [[Prototype]] set to null.

Another way to implement inheritance is to use constructors. Each function has a writable prototype attribute, which is automatically set to inherit from Object.prototype by default. You can change the prototype chain by overwriting it.


function Rect(length,width){
  this.length = length;
  this.width = width;
}
Rect.prototype.getArea = function(){
  return this.width * this.length;
};
Rect.prototype.toString = function(){
  return "[Rect"+this.length+"*"+this.width+"]";
};
function Square(size){
  this.length = size;
  this.width = size;
}
//修改prototype属性
Square.prototype = new Rect();
Square.prototype.constructor = Square;
Square.prototype.toString = function(){
  return "[Square"+this.length+"*"+this.width+"]";
};
var rect = new Rect(5,10);
var square = new Square(6);
console.log(rect.getArea()); //50
console.log(square.getArea()); //36

If you want to access the toString() of the parent class, you can do this:


Square.prototype.toString = function(){
  var text = Rect.prototype.toString.call(this);
  return text.replace("Rect","Square");
}

Related recommendations:

New understanding of JavaScript object-oriented

javascript object-oriented definition member method instance analysis

JavaScript object-oriented foundation and specific analysis of this pointing problem

The above is the detailed content of Detailed explanation of JavaScript object-oriented examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software