How do I retrieve a property from a prototype'

2019-07-07 06:54发布

问题:

I think the question explains itself. I am trying to retrieve a specific property that is inside a prototype's object that is inside a constructor object. If I cannot retrieve it, I wish someone would explain why I cannot. Here is the code from jsfiddle

Javascript

function animal() {
    this.name = "animal";
    this.action = "acting";
    this.active = function () {
        var txt = "This " + this.name + ", is " + this.action;
        attach('ex1', txt, 'p');
    }

}

function print(value) {
    document.getElementById('ex1').innerHTML += value;
}

function Human() {
    animal.call(this);

    Human.prototype = {
        name: "human",
        action: "conquering"

    }

}



var bob = new Human;

print(bob.name);

回答1:

It is quite simple, you are shadowing name with animal. Property fetching works like this. When you call obj.x it looks for property named x in obj. If it finds it, it returns value of that property, otherwise it looks for property x in constructor proptotype, if it find it it returns it. If it does not find it it looks in prototype objects constructor prototype, and so on till last prototype which is Object {}. If it does not find it, undefined is returned.

For more info look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

So in your case, bob has property name and its value is animal. You added this property to bob when you called animal function with context set to this in Human controller.

Maybe it example will help you understand prototype chain better:

function A() {
  this.x2 = 2;
}

A.prototype.x3 = 3;

function B() {
  this.x1 = 1;
}
B.prototype = new A();

const b = new B();
const b2 = new B();
b2.x3 = 'something';

console.log(b.x1); //found on b
console.log(b.x2); //found on B.prototype
console.log(b.x3); //found on A.prototype
console.log(b2.x3); //shadowed by b2.x3



回答2:

Why you can't retrieve a prototype's object property which has the same name as initial object's existing own property :

...
When a property is read on an object, the JavaScript engine first looks for an own property with that name. If the engine finds a correctly named own property, it returns that value. If no own property with that name exists on the target object, JavaScript searches the [[Prototype]] object instead. If a prototype property with that name exists, the value of that property is returned. If the search concludes without finding a property with the correct name, undefined is returned.

from The principles of object-oriented JavaScript / by Nicholas C. Zakas