繁体   English   中英

使用.prototype为变量添加方法

[英]Using .prototype for adding method to variable

我正在尝试分析此代码,但遇到了一些麻烦。 我的麻烦始于这一行。 Customer.prototype = new Person(); 现在据我所知。 我们可以像对Person.prototype.getName一样向变量添加一些方法。 太好了,现在Person具有指向返回名称的函数的proto 那么,当我们执行Customer.prototype = new Person();时,这意味着什么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());

通过执行Customer.prototype = new Person()我们实际上是在进行另一类语言的类继承。 所以,说我们有:

var p = new Person();
Customer.prototype = p;
var c = new Customer();

的原型(__proto__) cp和原型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的构造函数(除非您实际上是在创建一个真实的对象,否则通常不希望使用它)。

每个对象都有一个原型,它也是一个对象。

当你做

Customer.prototype = new Person();

...您设置了Customer的原型对象。 方法和属性不会复制到Customer对象中,但是当您在Customer上引用属性/方法时,将遵循原型链来查找该属性/方法。

对于myCustomer.sayMyName ,JavaScript引擎首先查看myCustomer的拥有属性,然后查看其原型(即Person对象),然后最后查看Person的原型(即具有该方法的对象):

Person.prototype.sayMyName = function() {
  alert('Hello, my name is ' + this.getName());
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM