[英]Prototype in Javascript code confusion
function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } // Greeting Person.prototype.greeting = function() { return `Hello there ${this.firstName} ${this.lastName}`; } // Customer constructor function Customer(firstName, lastName, phone, membership) { Person.call(this, firstName, lastName); this.phone = phone; this.membership = membership; } // Inherit the Person prototype methods Customer.prototype = Person; let detail1 = new Customer("hom", "kom", 989, "l"); detail1.greeting() // it is producing error that greeting is not a function
Why when I am running detail1.greeting() is producing an error even though I have set the prototype. 为什么当我运行detail1.greeting()时,即使我已经设置了原型,也会产生错误。
Customer.prototype = Person;
won't tie a Customer
's methods to Person.prototype
's methods, because the methods aren't on Person
itself, but on Person.prototype
. 不会将Customer
的方法Person.prototype
到Person.prototype
的方法,因为这些方法不是Person
本身,而是Person.prototype
。 While you could do Customer.prototype = Person.prototype
, that's probably not desirable, because then mutations to Customer.prototype
would affect Person.prototype
as well. 虽然你可以做Customer.prototype = Person.prototype
,但这可能是不可取的,因为Customer.prototype
突变也会影响Person.prototype
。
For Customer.prototype
to inherit Person.prototype
's methods, you should have Customer.prototype
be an object whose internal prototype is Person.prototype
, which can be done with Object.create
: 要使Customer.prototype
继承Person.prototype
的方法,您应该将Customer.prototype
作为其内部原型为Person.prototype
的对象,可以使用Object.create
完成:
Customer.prototype = Object.create(Person.prototype);
function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } // Greeting Person.prototype.greeting = function() { return `Hello there ${this.firstName} ${this.lastName}`; } // Customer constructor function Customer(firstName, lastName, phone, membership) { Person.call(this, firstName, lastName); this.phone = phone; this.membership = membership; } // Inherit the Person prototype methods Customer.prototype = Object.create(Person.prototype); let detail1 = new Customer("hom", "kom", 989, "l"); console.log(detail1.greeting()) // it is producing error that greeting is not a function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.