javascript - 为什么我们不能调用原型(prototype)函数?

标签 javascript class inheritance prototypal-inheritance

最初我将函数对象分配给变量 Person。此时,Person的proto指向Function.prototype。然后我向 Person.prototype 添加了一些函数。当我使用下面的 new 关键字调用 Person 构造函数并将其分配给 var test 时,据我所知,它将 test proto 设置为 Person.prototype。这个 Person.prototype 是一个对象, getName 映射到一个函数。因此,当我调用 test.getName() 时,它会在 test.prototype 中搜索该函数,如果在那里找不到该函数,那么它将在其 proto 中搜索该函数,即 Person.prototype .

现在假设我创建另一个函数对象并将其分配给变量 Customer。它的proto将指向Function.prototype。然后对于继承,我们应该这样做 Customer.prototype = new Person()。我很困惑为什么我应该这样做?是否将客户的原型(prototype)设置为Person.prototype。如果确实如此,那么我不应该只写 Customer = new Person().如果没有,客户 proto 是否仍然指向 Function.prototype 或者还有其他我遗漏的东西?

var Person = function(name) {
    this.name = name;
    console.log("Running the constructor of Person " + name)
}

Person.prototype.getName = function() {
    return this.name;
}

var test = new Person("Yolo");
console.log(Person.prototype.getName.call(test))
console.log(test.getName());

var Customer = function(name) {
    this.name = name;
    console.log("Running the constructor of Customer " + name)
};

Customer.prototype = new Person();

提前致谢!

最佳答案

这里有两个不同的概念:

  • __proto__ 是继承树中对象的父对象。
  • prototype 是一个函数的属性,它定义了它在用作构造函数时创建的任何对象的 __proto__ 的内容。

由于构造函数本身就是对象(函数对象),因此它们也位于继承树中,但该树与这些构造函数创建的对象的继承树无关。他们是两个不同的世界。

看一下这段代码,它说明了客户对象的继承链:

var cust = new Customer('Jack');
console.log(cust.__proto__ === Customer.prototype); // true
console.log(cust.__proto__.__proto__ === Person.prototype); // true
console.log(cust.__proto__.__proto__.__proto__ === Object.prototype); // true

所以这里我们遵循cust对象的原型(prototype)链。这是与构造函数(函数)的链完全不同的链:

console.log(Customer.__proto__ === Function.prototype); // true
console.log(Person.__proto__ === Function.prototype); // true
console.log(Object.__proto__ === Function.prototype); // true

这里没有什么不寻常的:它们是函数。此外,没有必要对此进行任何更改。如前所述,它与这些构造函数创建的对象的继承无关。

请注意,您永远不需要访问 __proto__ 属性。以上只是为了说明继承链。

关于javascript - 为什么我们不能调用原型(prototype)函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38420488/

相关文章:

Javascript/Rails - 如何在 javascript 中包装 link_to 而不是 <an></a>

javascript - 检查 URL 是否会在加载到 iFrame 后重定向父页面

c++ - 无法从 'SDL_Surface' 转换为 'SDL_Surface MainMenu::*'

Ruby - 类方法中的引用子类

c++ - const char数组多重初始化c++

javascript - 将函数分配为原型(prototype)函数的属性

javascript - 如何根据元素显示正确的计算值?

C++ 指针和类

java - 如何让输入决定使用哪个类?

c++ - 多层继承C++