为什么我们不能调用原型函数?

Why cannot we call prototype functions?

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

现在假设我创建了另一个函数对象并将其分配给变量 Customer。它的 proto 将指向 Function.prototype。那么对于继承,我们应该做 Customer.prototype = new Person()。我很困惑为什么我应该这样做?它是否将客户的 proto 设置为 Person.prototype。如果确实如此,那么我不应该只写 Customer = new Person()。如果不是,那么 Customer 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();

提前致谢!

Customer.___proto____ = Function.prototype 

它将始终指向函数原型

Customer.prototype = new Person();

这条语句将使Customer.prototype._____proto_____指向Person.Prototype

Customer._____proto_____ 永远不会改变只有它的原型的 ____proto___ 通过继承

改变

我发现这张图片很有用。它清楚地显示了所有链接。

这里有两个不同的概念:

  • __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对象的原型链。这是一个与构造函数(函数)的链完全不同的链:

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

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

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