"JavaScript you don't Know" prototype

Source: Internet
Author: User

1 [[Prototype]]

[[Prototype]] is a reference to other objects, and almost all objects are given a non-null value when they are created [[Prototype]] property.

var myObject = {      A:2}myobject.a;   //   2  

Referencing an object property triggers the [[Get]] action, which checks to see if the object itself has this property, and if so, uses it, but a is not myobject, and the [[Prototype]] chain of the object needs to be used.

When traversing an object with a for in principle, similar to finding [[Prototype]] chains, any property that can be accessed through the prototype chain is enumerated. Use the In operator to check if an object exists or to find the entire prototype chain of an object.

var anotherobject = {      A:2}var myObject = object.create (anotherobject  );  for (var in myObject) {    console.log (k);}

1.1 Object.prototype

All ordinary [[Prototype]] chains end up pointing to the built-in Object.prototype. Since all "normal" (built-in, many extensions of a particular host) object originates from this object.prototype, it contains many common features of JavaScript.

1.2 Property settings and masking

Myobject.foo = "Bar";

If Foo is not directly present in the Myobject,[[prototype]] chain is traversed, if the prototype chain is not found Foo,foo will be added to MyObject.

If Foo does not exist directly in MyObject but is present in the upper layer of the prototype chain:

    1. If a normal data access property named Foo is present at the top of the [[Prototype]] chain and is not marked as read-only (Writeable:false), add the Foo attribute directly in MyObject, which is the masking property .
    2. If Foo is present on the [[Prototype]] chain, but it is marked as read-only, you cannot modify an existing attribute or create a masking property on MyObject . Errors are thrown in strict mode, otherwise this statement is ignored.
    3. If Foo is present on the [[Prototype]] chain and it is a setter, then the setter will be called. Foo will not be added to MyObject, nor will it redefine Foo.

If the subtle second and third cases also mask foo, you cannot use = assignment, but instead use Object.defineproperty () to add Foo to MyObject.

varAnotherobject ={A:2}varMyObject =object.create (anotherobject); anotherobject.a; //2MYOBJECT.A;//2Anotherobject.hasownproperty ("A");//trueMyobject.hasownproperty ("a");//falsemyobject.a++;//Implicit shieldinganotherobject.a; //2MYOBJECT.A;//3Myobject.hasownproperty ("A");//true

+ + operation equals MYOBJECT.A = Myobject.a + 1. The + + operation first finds the property a by [[Prototype]] and obtains the current property value 2 from Anotherobject.a, then adds 1 to it, and then assigns 3 to the new masked property A of myobejct with [[Put]].

If you want to increase the value of ANOTHEROBJECG, the only way is to anotherobject.a++.

2 "Class" 2.1 "Class" function
function Foo () {}foo.prototype;   //   {}

This object is created when calling new Foo () and is then associated with "Foo Point prototype".

function foo () {} var New  = = object.getprototypeof (a)  //  true

Call new Foo () to create a, and one of the steps is to connect A's [[Prototype]] tothe object that foo. Prototype points to.

2.2 "Constructors"
function= = = Foo;  // true var New  = = = Foo;  //   True

Foo.prototype Default has a public and non-enumerable property. Constructor, which refers to the object-associated function (Foo). The object created by calling new Foo () through the constructor also has a. Constructor property, which points to "create this object's function."

When you precede a normal function call with new, the function call becomes a "constructor call." New will hijack the normal function and call it in the form of a constructed object.

function nothingspecial () {    console.log ("Don t Mind Me");} var New // {}

Nothingspecial is just a normal function, but when called with new, it constructs an object and assigns a value to a.

The most accurate explanation for "constructors" in JavaScript is that all function calls with new.

2.3 Technology

A.constructor = = = Foo is true, does not mean that a has a. constructor property that points to Foo. The constructor reference is also delegated to Foo.prototype,foo.prototype.constructor by default to Foo. A.constructor only points to Foo by default [[prototype]] delegation.

Foo.prototype. Constructor property is just the default property of the Foo function at the time of declaration. If you create a new object and replace the default. prototype object reference for the function, the new object is not automatically obtained. Constructor property.

function /* ... */ /*... */ }varnew= = = Foo;  //   false true  //   True

A1 does not have a. Constructor property, which delegates foo.prototype on the [[Prototype]] chain. But this object is not. The constructor property (has been modified), so it will continue to delegate to the Object.prototype at the top of the delegate chain. The. Constructor property of this object points to the built-in object function.

3 (prototype) inheritance
functionFoo (name) { This. Name =name;} Foo.prototype.myName=function() {    return  This. Name;functionBar (name, label) {Foo.call ( This, name);  This. Label =label;}//creates a new Bar.prototype object and associates it to the Foo.prototypeBar.prototype =object.create (foo.prototype);//There are no Bar.prototype.constructor now and need to be repaired manuallyBar.prototype.myLabel =function() {    return  This. Label;}varA =NewBar ("A", "obj a"); A.myname (); //"a"A.mylabel ();//"obj a"

Calling Object.create () creates a "new" object in thin Air and associates [[Prototype]] inside the new object with the object (foo.prototype) you specify.

Bar.prototype = object.create (foo.prototype) means "Create a new Bar.prototype object and associate it to Foo.prototype".

// Error Procedure //   not the same as the desired mechanism Bar.prototype = foo.prototype; // may have side effects New Foo ();

Bar.prototype = Foo.prototype just let Bar.prototype directly refer to the Foo.prototype object. So perform such as Bar.prototype.mylabel = ... Assignment statements directly modify the Foo.prototype object itself.

Bar.prototype = new Foo () creates an object associated to Bar.prototype, but it uses a constructor call, if the function Foo has some side effects (such as writing logs, modifying state, registering to other objects, adding data attributes to this), Will affect the "Descendants" of Bar ().

Check the class relationship

In a traditional class-oriented environment, the inheritance ancestor (JavaScript's delegate relationship) that examines an instance (JavaScript object) is often turned into introspection (or reflection).

function Foo () {    //  ... = ...; var New Foo ();

The first method: a instanceof Foo; True

Instanceof determines whether the entire [[Prototype]] chain of a has an object pointing to Foo.prototype. However, this method can only handle the relationship between objects and functions.

The second method: Foo.prototype.isPropertyOf (a); True

4 Object Associations

The [[Prototype]] mechanism is an internal link that exists in an object that references other objects. Usually it does this: if you don't find the desired property or method reference on the object, the engine will continue to look on the object associated with [[Prototype]]. The link to this series of objects is referred to as the "prototype chain".

4.1 Creating associations
var foo = {    function() {        console.log ("Tell me someting goos.") );    }} var bar = object.create (foo); bar.something ();    // Tell   me someting goos.

Object.create creates a new object and associates it to the specified object (foo).

object.create (NULL) creates an object with an empty (or null) [[Prototype]] link, which cannot be delegated. Because he does not have a prototype chain, so instanceof can not judge, always return false. These special empty [[Prototype]] objects are often referred to as "dictionaries", which are completely unaffected by the prototype chain and are ideal for storing data .

Object.create's Polyfill code

Object.create is ES5 new function, in the environment before ES5 to support this function to use this code, it implements the obejct.create part of the function

if (! object.create) {    function(o) {        function  F () {};         = o;         return New F ();    }}

This code uses a one-time function F, by overwriting its. prototype to point to the object that you want to associate, and then using new F () to construct a new object to associate with. The second parameter of Object.create specifies the property names that need to be added to the new object and the property descriptors for those properties, but the previous version of ES5 cannot impersonate the property descriptor.

4.2 Association relationships are a must

Assuming that you want to invoke Myobject.cool (), the API will be "magical" if Cool () does not exist in MyObject.

var anotherobject = {    function() {        console.log ("cool!") );    }} var myObject = object.create (anotherobject); Myobject.cool ();    //   cool!

var anotherobject = {    function() {        console.log ("cool.") );    }} var myObject =function() {    this. Cool ();  //   Internal entrustment }myobject.docool ();  

The emphasis here Myobject.docool () is actually present in MyObject, making the API design clearer. Internally, this implementation follows the delegate design pattern , which is delegated to Anotherobject.cool () via [[Prototype]].

Internal delegation can make API interface design clearer than Direct delegation .

A JavaScript prototype you don't know

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.