Home > Web Front-end > JS Tutorial > body text

Understanding JavaScript's prototype attribute_javascript tips

WBOY
Release: 2016-05-16 17:56:18
Original
678 people have browsed it

In fact, prototype can be summarized in just a few sentences:
Any prototype is an object, and only objects have prototypes
Only Function has the prototype attribute, which is the prototype inherited by the object generated when this Function is used as a constructor. The prototype of a Function has nothing to do with its prototype attribute
The prototype of an object can be accessed through the non-standard attribute __proto__ or the ECMAScript5 method Object.getPrototypeOf().
1 is actually wrong. Object, the object at the end of the prototype chain, has no prototype. But for the sake of simpler expression. After looking at the prototype chain, you will understand how undefined methods such as .toString() come from.
The ambiguity mentioned above is based on literal understanding, and there is no ambiguity in the grammar itself. Prototype means prototype, but the prototype of an object is not accessed by prototype.
Function has a prototype attribute, but it has nothing to do with its own prototype. After understanding this, it will be much easier to understand if you read articles about prototype chain and inheritance.

Here are some examples to deepen your understanding:

Copy the code The code is as follows:

// Any object has a prototype
obj = {};
console.log( obj.__proto__ );
console.log( Object.getPrototypeOf(obj) );
console. log( obj.__proto__ === Object.getPrototypeOf(obj) );

//The object does not have a grammatically meaningful prototype attribute
alert(obj.prototype) //undefined

//prototype, as an attribute, only exists in Function, representing the prototype integrated with the new instance created by this Function, and has nothing to do with the prototype of Function itself
var F = function(name){
this.name = name ;
}
obj = {a:3,
get b (){
return this.a;
}
};
F.prototype = obj;
newObj = new F('new name');
newObj.name; //As a constructor, name is newObj's own property
newObj.a; //3
//It inherits obj. It can be confirmed by:
Object.getPrototypeOf( newObj ) === obj; // true
newObj.__proto__ === obj; //true
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!