【发布时间】:2016-07-17 10:58:45
【问题描述】:
最初我将函数对象分配给变量 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()。我很困惑为什么我应该这样做?是否将客户的 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();
提前致谢!
【问题讨论】:
-
提示:
var test = new Person()和var Test.prototype = new Person()有什么区别
标签: javascript class inheritance prototypal-inheritance