我认为这个问题本身就很解释。我正在尝试检索构造函数对象内原型对象内部的特定属性。如果我无法检索它,我希望有人能解释为什么我不能检索它。这是来自的代码jsfiddle https://jsfiddle.net/786ze44b/
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);
很简单,你用动物来命名名字。
属性获取的工作原理如下。
当您调用 obj.x 时,它会在 obj 中查找名为 x 的属性。如果找到它,它将返回该属性的值,否则它会在构造函数 proptotype 中查找属性 x,如果找到它,则返回它。如果没有找到它,它会在原型对象构造函数原型中查找,依此类推,直到最后一个原型,即 Object {}。如果没有找到,则返回 undefined。
欲了解更多信息,请看这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
因此,在您的情况下,鲍勃有属性名称,其值是动物。当您调用动物函数并将上下文设置为人类控制器中的此属性时,您将此属性添加到 bob 中。
也许这个例子会帮助你更好地理解原型链:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)