如何从构造函数内部的原型对象中检索属性 [英] How do I retrieve a property from a prototype's object that is inside a constructor function

查看:98
本文介绍了如何从构造函数内部的原型对象中检索属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这个问题解释了。我正在尝试检索构造函数对象内的原型对象内的特定属性。如果我无法找回它,我希望有人能解释为什么我不能。以下是来自 jsfiddle 的代码

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

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。

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.

有关详细信息,请查看此处:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

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

所以在你的情况下,bob有属性名称,它的值是动物。当你在人类控制器中调用了上下文设置为动物函数的动物函数时,你将这个属性添加到了bob。

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

这篇关于如何从构造函数内部的原型对象中检索属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆