JavaScript prototype chain issue

Why can't I access property β€œx” from A?

A = {}; B = {y: 'y'}; C = {x: 'x'}; A.prototype = B; B.prototype = C; Ax 
+4
source share
1 answer

The prototype of the object is not reflected in the prototype property (confuse, although it may be). In fact, there is no standard direct way to install a prototype of an object after its creation (and more recently, there was a standard tool for obtaining a prototype of an object). In the code you specified, all you did was create a normal prototype property for the objects; it can also be called foo . foo

JavaScript has a special prototype property, but it is on functions: it is an object that will be assigned as a prototype of the objects created by this function if you use it with the new keyword (for example, as a constructor function). In fact, until recently, the only way to assign a prototype to an object was a constructor function:

 function makeA() { } makeA.prototype.x = "foo"; A = new makeA(); alert(Ax); // alerts "foo" 

... and that this is the only widespread remedy for this.

Things change a bit with the new ECMAScript 5th edition specification , but you can still only set up a prototype of an object when it is created, not after the fact. What the new material does allows you to do it directly, rather than making a constructor function for this. This is the new Object.create feature in section 15.2.3.5, but it has not yet been widely adopted. (There are several other great features of the 5th edition, including the ability to get a prototype of an object through Object.getPrototypeOf , but there’s still no way to change it after the fact.)

There is a non-standard property that some implementations (for example, the Firefox SpiderMonkey engine) provide __proto__ , but are not widely supported and are not included in the latest specification.

Using the new Object.create , you can do what you want:

 var C = {x: 'x'}; var B = Object.create(C); By = 'y'; var A = Object.create(B); alert(Ax); // alerts "x" 

... but since Object.create is so new, you will find that in most implementations you need to create it because it does not exist. This is easy enough if we ignore its second argument (which can only be partially emulated):

 if (!Object.create) { // An *incomplete* emulation of Object.create, doesn't support the optional // second parameter defined by the spec. Object.create = function(proto) { var obj; // There no point in calling this with a null or otherwise "falsy" // prototype, but let handle it if you do if (!proto) { return {}; // Just a generic object } // Define a constructor object that uses // the prototype function ctor() { } ctor.prototype = proto; // Create and return the object return new ctor(); }; } 
+8
source