Understanding prototype concepts in JavaScript programming-Basic Knowledge-js tutorial

Source: Internet
Author: User
This article mainly introduces the concept of prototype in JavaScript programming, including the use of prototype attributes and other related knowledge. For more information, see the prototype object of JavaScript. Even experienced JavaScript experts and even their authors often give a very limited explanation of this concept. I believe the problem comes from our earliest understanding of prototype. The prototype is always closely related to the new, constructor, and confusing prototype attributes. In fact, prototype is a simple concept. To better understand it, we need to forget the prototype of what we learned, and then trace the source.

What is prototype?

A prototype is an object that inherits attributes from other objects.

Can any object be a prototype?

Yes

Which objects have the original type?

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

What is the object?

In JavaScript, an object is an unordered set stored by a key-value pair. If it is not an original class (undefined, null, boolean. nuber or string), it is an object.

You can think that each object has a prototype. But when I write ({}). prototype, I get undefined. Are you crazy?

Forget your understanding of prototype attributes-this is probably the root of confusion. the true prototype of an object is the internal [[Prototype] attribute. ECMA 5 introduces the standard access method, Object. getPrototypeOf (object ). This latest implementation has been supported by Firefox, Safari, Chrome and IE9. besides IE, all browsers support non-standard access methods _ proto __. otherwise, we can only say that the object construction method is its prototype attribute.

Var a ={}; // failed Object under Opera or IE <= 8. getPrototypeOf (a); // [object Object] // failure under IE. _ proto __; // [object Object] // all browsers // (but only if constructor. prototype has not been replaced and fails with Object. create). constructor. prototype; // [object Object]


Good. false is the original type. Why does false. _ proto _ return a value?

When accessing the prototype of the original type, it is forcibly converted into an object.

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

I want to use prototype to implement inheritance. What should I do now?

Adding a prototype attribute to an instance is meaningless. unless otherwise, it is very efficient to add attributes directly to the instance itself. suppose we already have an object to share the functions of an existing object. for example, Array, we can do this

//fails in IE<=8var a = {};a.__proto_ = Array.prototype;a.length; //0

However, we can see that the real strength of the prototype is that multiple instances share the same prototype. The attributes of a prototype object can be inherited by all instances referenced by the prototype object only once. The effects of prototype on performance and program maintainability are obvious. So is this the cause of the constructor? Yes, constructor provides a convenient cross-browser mechanism to allocate a public prototype when an instance is created ..


Before giving an example, I need to know what constructor. prototype property is?

Well, first, JavaScript does not distinguish between constructors and other methods, so each method has the prototype attribute. Instead, none of the methods have such attributes.

// It is never a constructor method. In any case, it is a Math with the prototype attribute. max. prototype; // [object Object] // The constructor also has the prototype attribute var A = function (name) {this. name = name;}. prototype; // [object Object] // Math is not a method, so there is no prototype attribute Math. prototype; // null

It can be defined now: the prototype attribute of a method is the prototype object assigned to the instance when the method is used as a constructor to create an instance.

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

// (It will fail in IE) var A = function (name) {this. name = name;}. prototype =. _ proto __; // falseA. _ proto _ = Function. prototype; // prototype of true-A is the prototype attribute of its constructor.

Can you give an example?

The following code may have been seen or used hundreds of times, but you have moved it here, but it may be somewhat innovative.

// Constructor.ThisThe [[prototype] attribute inside the new object will be set as the default prototype attribute var Circle = function (radius) {this. radius = radius; // next line is implicit, added for authentication only // this. _ proto _ = Circle. prototype;} // expands the attributes of the default prototype object of Circle. Therefore, it expands the attribute Circle of each prototype object created by it. prototype. area = function () {return Math. PI * this. radius * this. radius;} // create two examples of Circle. Each example uses the same prototype attribute var a = new Circle (3), B = new Circle (4);. area (). toFixed (2); // 28.27b.area (). toFixed (2); // 50.27

This is great. If I change the prototype attribute of constructor, can I access the new prototype immediately even if an existing instance object exists?

Well, not all. If I modify the attributes of the existing prototype, this is true, because a. _ proto _ references the object defined by A. prototype during object creation.

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


However, 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 with the constructor attribute.

Var A = function () {};. prototype. constructor = A; // true var a = new A ();. constructor = A; // true (the constructor attribute of a inherits from its prototype)


What is the relationship between instanceof and prototype?
If the prototype attribute of A appears in the prototype chain of a, the expression a instanceof A returns true. This means we can fool instanceof and invalidate it.

var A = function() {} var a = new A();a.__proto__ == A.prototype; //true - so instanceof A will return truea instanceof A; //true; //mess around with a's prototypea.__proto__ = Function.prototype; //a's prototype no longer in same prototype chain as A's prototype propertya instanceof A; //false


So what else can I do with the prototype?

I have said that each constructor has a prototype attribute, which can be used to assign a prototype to all instances generated by the constructor? In fact, this applies to local constructors, such as functions and strings. By extending (rather than replacing) This attribute, we can update the prototype of each specified type 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

Related Article

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.