Deep understanding of prototype concepts in JavaScript programming-basics

Source: Internet
Author: User
Tags object object

JavaScript's archetypal objects are always tangled. Even experienced JavaScript experts and even their authors often give a very limited explanation of the concept. I believe the problem comes from our earliest understanding of the archetype. Prototypes are always closely associated with new, constructor, and confusing prototype attributes. In fact, a prototype is a fairly simple concept. To better understand it, we need to forget the stereotype we ' learned ' and then trace it.

What is a prototype?

A prototype is an object that inherits an attribute from another object.

Is it possible for any object to be a prototype?

Yes

Those objects have prototypes?

Each object has a default prototype. The prototype itself is an object, and each prototype itself has a prototype. (with one exception, the default object prototype is at the top of each prototype chain, and the other prototypes are behind the prototype chain)

What is the object, if you step back?

In JavaScript, an object is an arbitrary, unordered collection of key-value pairs, which is an object if it is not the original class (Undefined,null,boolean.nuber or String).

You can assume that each object has a prototype. But when I write ({}). prototype, I got undefined, are you crazy?

Forget what you know about the prototype attribute-this is probably the source of the confusion. The real Prototype of an object is the internal [[Prototype]] property. ECMA 5 describes the standard access method, Object.getprototypeof (Object). This latest implementation has been supported by Firefox, Safari, Chrome and IE9. In addition, in addition to IE, all browsers support non-standard access methods __proto__. Otherwise, we can only say that the object's construction method is its prototype attribute.

var a = {};
 
Opera or ie<=8 failure
object.getprototypeof (a);//[object Object]
 
//ie failure
a.__proto__;//[object Object] /
 
/All browsers
//(but only if Constructor.prototype has not been replaced and fails with object.create)
a.construct Or.prototype; [Object Object]


good, False is the original type, why does false.__proto__ return a value ?

When the original type's prototype (prototype) is accessed, it is coerced into an object.

(works with ie<=8 too, due to double-negative)
false.__proto__ = = Boolean (false). __proto__;//true

I want to use the prototype to implement inheritance, what should I do now?

Adding a prototype attribute to an instance is almost meaningless. Unless, in one case, it's very efficient. Adding attributes directly to the instance itself. Suppose we already have an object that shares the functionality of an existing object. For example array we can do this

Fails in ie<=8
var a = {};
A.__proto_ = Array.prototype;
A.length; 0

But we can see that the real strength of the prototype is that multiple instances share the same prototype. The properties of a prototype object are only defined once and can be inherited by all instances that it references. The effect of using prototypes on performance and program maintainability is obvious. So is that why the constructor is generated? Yes, the constructor provides a convenient cross-browser mechanism to implement common prototyping assignments when the instance is created ...


before giving an example, I need to know what Constructor.prototype is for?

Well, first of all, JavaScript does not differentiate between constructors and other methods, so each method has a prototype attribute. Instead of anything that is not a method, there is no such attribute.

A method that is never a constructor, however, is a Math.max.prototype with a prototype attribute
;//[object Object]
 
//constructor also has prototype attribute
var a = function (name) {
  this.name = name;
}
A.prototype; [Object]
 
//math is not a method, so there is no prototype attribute
Math.prototype;//null

You can now define that the prototype property of a method is the object of the prototype that is assigned to the instance when the method is used as a constructor to create the instance.

It is very important to understand that the prototype property of the method has nothing to do with the actual prototype.

(will fail in IE)
var A = function (name) {
  this.name = name;
}
 
A.prototype = = a.__proto__; False
a.__proto__ = = Function.prototype//true-a prototype is the prototype property of its constructor

Can I give you an example?

The following code, you may have seen or used hundreds of times, but here again to move it up, but there may be some new ideas.

constructor. <em>this</em> returns as a new object and its internal [[prototype]] property will be set to the constructor default prototype property
var Circle = function (RADIUS) {
  This.radius = radius;
  Next line are implicit, added for illustration only
  //this.__proto__ = Circle.prototype;
}
 
Expanding the properties of the default prototype object for Circle therefore expands the properties
Circle.prototype.area = function () {Return of each prototype object that it creates a new instance of.
  Math.pi*this.radius*this.radius;
}
 
Create two examples of Circle, each using the same prototype attribute
var a = new Circle (3), B = new Circle (4);
A.area (). toFixed (2); 28.27
B.area (). toFixed (2);//50.27

It's great. If I change the prototype attribute of constructor, can even an existing instance object immediately access the new prototype version?

Well...... Not exactly. This is true if I modify the properties of an existing prototype, because A.__PROTO__ references the object defined by A.prototype when the object is created.

var A = function (name) {
  this.name = name;
}
 
var a = new A (' alpha ');
A.name; ' alpha '
 
a.prototype.x = n;
 
a.x; 23


But if I replace the prototype property with a new object, a.__proto__ still points to the original object.

var A = function (name) {
  this.name = name;
}
 
var a = new A (' alpha ');
A.name; ' alpha '
 
a.prototype = {x:23};
 
a.x; Null

What is a default prototype?

An object that owns the constructor property.

var A = function () {};
A.prototype.constructor = = A; True
 
var a = new A ();
A.constructor = = A; True (A's constructor property inherits from its prototype)


What's the relationship between instanceof and prototype?
If A's prototype property appears in the prototype chain of a, then expression a instanceof a returns true. This means that we can cheat instanceof and let it fail.

var a = function () {}
 
var a = new A ();
a.__proto__ = = A.prototype; True-so instanceof A'll return True
a instanceof A;//true;
 
Mess around with a ' s prototype
a.__proto__ = Function.prototype;
 
A ' s prototype no longer in same prototype chain as A's prototype property
a instanceof A;//false


So what else can I do with the prototypes?

Remember when I said that each constructor has a prototype attribute that can be used to assign a prototype to all instances generated by the constructor? This also applies to local constructors, such as function and string. By extending (rather than replacing) this property, we can update the prototype of each specified type of object.

String.prototype.times = function (count) {return
  count < 1? ': New Array (count + 1). Join (this);
 
Hello! ". Times (3); "Hello!hello!hello!"; "
Please ... ". Times (6); "Please...please...please...please...please...please ..."

Tell me more about inheritance and how prototypes work. What is a prototype chain?


Because each object and each prototype (itself) has a prototype, we can imagine that one after another objects are connected together to form a prototype chain. The terminal of the prototype chain is always the prototype of the default object.

a.__proto__ = b;
b.__proto__ = C;
c.__proto__ = {}; Default object
{}.__proto__.__proto__;//null


The prototype inheritance mechanism is internally and implicitly implemented. When object a accesses property foo, JavaScript traverses the prototype chain of a (starting with a itself) to check the Foo attribute that exists in each link of the prototype chain. If the Foo property is found, it is returned, otherwise the undefined value is returned.

What happens when you assign a value directly?

When you assign a value directly to an object property, the prototype inheritance mechanism does not play. a.foo= ' Bar ' will be assigned directly to the Foo property of a. To assign values to the properties of a prototype object, you need to locate the property of the prototype object directly.
It's all about JavaScript prototypes. I think the concept of the prototype understanding, I grasp the more accurate, but my point of view is not the final result. Please feel free to tell me the wrong place or to put forward an opinion that is inconsistent with me.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.