我正在寻找分析此代码而我遇到了一些麻烦。我的麻烦从这条线开始。 Customer.prototype = new Person();
。现在据我所知。我们可以像使用Person.prototype.getName
一样为变量添加一些方法。好的,现在Person
有一个proto
指向一个返回名称的函数。那么当我们做Customer.prototype = new Person();
时意味着什么呢?这是否意味着采用Person
中的所有方法和语句并将它们放在变量Customer
中?
var Person = function(name) {
this.name = name;
};
Person.prototype.getName = function() {
return this.name;
};
var john = new Person("John");
//Try the getter
alert(john.getName());
Person.prototype.sayMyName = function() {
alert('Hello, my name is ' + this.getName());
};
john.sayMyName();
var Customer = function(name) {
this.name = name;
};
Customer.prototype = new Person();
var myCustomer = new Customer('Dream Inc.');
myCustomer.sayMyName();
Customer.prototype.setAmountDue = function(amountDue) {
this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function() {
return this.amountDue;
};
myCustomer.setAmountDue(2000);
alert(myCustomer.getAmountDue());
答案 0 :(得分:1)
通过执行Customer.prototype = new Person()
,我们实际上正在使用另一种语言进行类继承。所以,说我们有:
var p = new Person();
Customer.prototype = p;
var c = new Customer();
c
的原型(__proto__)为p
,p
的原型为Person.prototype。
继承的天真方式是Customer.prototype = Person.prototype
,这将使Customer的所有实例共享与Person相同的方法。但是,如果我们做Customer.prototype.newMethod = ...
,它也会修改Person.prototype
的原型(因为它们是同一个对象。
为了区分Customer原型和Person原型,我们使用new Person()
作为链中的中间体,它仍然具有指向Person原型的链接,但是它是一个单独的对象。
注意:通常Customer.prototype = Object.create(Person)
后跟Customer.prototype.constructor = Customer;
更常规,因为执行new Person()
意味着调用了Person
的构造函数(除非你真正制作一个真实物体,否则通常不需要这样做。)
答案 1 :(得分:1)
每个对象都有一个原型,它也是一个对象。
当你这样做时
Customer.prototype = new Person();
...设置Customer
的原型对象。方法和属性不会被复制到Customer
对象中,但是当您在Customer
上引用属性/方法时,将遵循原型链来查找该属性/方法。
在myCustomer.sayMyName
的情况下,JavaScript引擎首先查看myCustomer
拥有的属性,然后查看其原型中的Person
对象,然后最终查看原型是Person
的对象,它是具有该方法的对象:
Person.prototype.sayMyName = function() {
alert('Hello, my name is ' + this.getName());
};