Can you help explain how to invoke the Javascript prototype inheritance method?

In this block of code:

var Fruit = function() {} Fruit.prototype = { color: function () { console.log('Fruit color...') } } var Apple = function () {} Apple.prototype = new Fruit() Apple.prototype.constructor = Apple var a = new Apple() Apple.prototype = null // the question!!! a.color() 

When Apple.prototype set to null , why does instance a still call the color method?

+6
source share
2 answers

You change the Apple.prototype link after , you created an instance of a .

Changing the link here does not change it for existing instances.

You will also find

 var a = new Apple(); Apple.prototype = {}; // some other object a instanceof Apple; // false 

i.e. because we changed the inheritance chain of Apple a no longer considered Apple.

Setting Foo.prototype = null will raise a TypeError if you try to do instanceof Foo validation


Changing the property of an object does not change the reference to this object. eg

 var foo = {}, bar = foo; foo.hello = 'world'; foo === bar; // true 

Changing the object itself changes the link

 foo = {hello: 'world'}; foo === bar; // false 

Or it’s described in more detail how the prototype refers to an instance,

 var Foo = {}, // pseudo constructor bar = {}, baz = {}; var fizz = {}; // fizz will be our pseudo instance Foo.bar = bar; // pseudo prototype fizz.inherit = foo.bar; // pseudo inheritance Foo.bar = baz; // pseudo new prototype fizz.inherit === foo.bar; // false, instance inheritance points elsewhere 

The best practice for setting up the inheritance chain is not using new , but using Object.create

 Apple.prototype = Object.create(Fruit.prototype); 

If you need the Fruit constructor called by Apple instances, you would do

 function Apple() { // this instanceof Apple Fruit.apply(this); // ... } 
+9
source

We need to understand what happens behind the line.

 var a = new Apple(); 

JavaScript uses prototype-based programming as its OOP style. This means that it creates a new object by cloning the old object, and not by creating a class. Given the JavaScript mechanisms of Gecko and Webkit, here's what happens behind the β€œnew” expression above:

 var a = clone(Apple.prototype); // this is an analogy to memcpy() in C/C++ a.__proto__ = Apple.prototype; // useful for the instanceof checking a.constructor = Apple; // a function a.constructor(); // so "this" in the called function means "a" 

So, both a.color and Apple.prototype.color are links to the same function that is located at, for example, 0xABCD, because the value 0xABCD was copied from Apple.prototype to a. Thus, the call to a.color () will be associated with the address 0xABCD, it has nothing to do with Apple.prototype, so you can freely set Apple.prototype to null.

It turns out that the above clone () function is actually a well-known Object.create () function. Object.create () also includes an assignment for the __proto__ property.

0
source

All Articles