Home >Web Front-end >JS Tutorial >Detailed explanation of examples of how to construct custom objects in javascript

Detailed explanation of examples of how to construct custom objects in javascript

伊谢尔伦
伊谢尔伦Original
2017-07-27 10:26:271165browse

There are two ways to create advanced object construction: using the "this" keyword construction and using the prototype prototype construction. For example:

//使用this关键字定义构造的上下文属性 
function Girl() 
{ 
this.name = "big pig"; 
this.age = 20; 
this.standing; 
this.bust; 
this.waist; 
this.hip; 
} 
//使用prototype 
function Girl(){} 
Girl.prototype.name = "big pig"; 
Girl.prototype.age = 20; 
Girl.prototype.standing; 
Girl.prototype.bust; 
Girl.prototype.waist; 
Girl.prototype.hip; 
alert(new Girl().name);

The two definitions in the above example are essentially the same. They both define the attribute information of the "Girl" object. The difference between "this" and "prototype" mainly lies in the order of attribute access. For example:

function Test() 
{ 
this.text = function() 
{ 
alert("defined by this"); 
} 
} 
Test.prototype.test = function() 
{ 
alert("defined by prototype"); 
} 
var _o = new Test(); 
_o.test();//输出“defined by this”

When accessing the properties or methods of an object, the rules for searching the prototype chain will be followed. First look for its own static properties and methods, then look for the accessible properties and methods of the construction context, and finally look for the prototype chain of the construction.

Another difference between the definitions of "this" and "prototype" is that the attributes occupy different spaces. Using the "this" keyword, the example initializes the space required for all properties and methods contained in the constructor for each instance, and uses the "prototype" definition, because "prototype" is actually a reference to the parent. , is just a copy of the data, so it saves resources in initialization and storage than "this".

The above is the detailed content of Detailed explanation of examples of how to construct custom objects in javascript. 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