如何解决如何访问覆盖的方法
我有以下几点:
// Person constructor
function Person(firstName,lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Greeting
Person.prototype.greeting = function(){
return `Hello there ${this.firstName} ${this.lastName}`;
}
const person1 = new Person('John','Doe');
// Customer constructor
function Customer(firstName,lastName,phone,membership) {
Person.call(this,firstName,lastName);
this.phone = phone;
this.membership = membership;
}
const customer = new Customer('Tom','Smith','555-555-5555','Standard');
// Inherit the Person prototype methods
Customer.prototype = Object.create(Person.prototype);
// Make customer.prototype return Customer()
Customer.prototype.constructor = Customer;
// Create customer
const customer1 = new Customer('Tom','Standard');
// Customer greeting
Customer.prototype.greeting = function(){
return `Hello there ${this.firstName} ${this.lastName} welcome to our company`;
}
因此对于customer1,我可以使用console.log(customer1.greeting()) 访问customer.greeting()。我如何访问 customer1 的 Person.greeting()?
更新:
Felix Kling 提供的答案很有趣,但似乎没有回答问题。他似乎在展示如何覆盖被覆盖的方法。我的问题是可以访问这两种问候方式,如果可以,如何访问?
如果我们使用类,我认为应该可以:
class Customer extends Person {
greeting(); //should return Customer.greeting()
super.greeting(); //should return Person.greeting()
}
这是否正确,是否可以在不使用类的情况下做同样的事情?
第二次更新
在 es5 中我们可以:
console.log(customer1.constructor.prototype.greeting.call(customer1))
或
console.log(Object.getPrototypeOf(customer1.constructor.prototype).greeting.call(customer1));
获取问候的父方法。我们可以使用:
customer1.greeting()
获取客户问候方式。
在 es6 中,我们可以使用类并执行以下操作:
class Person {
constructor(firstName,lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
greeting() {
return `Hello there ${this.firstName} ${this.lastName}`;
}
}
class Customer extends Person {
constructor(firstName,membership) {
super(firstName,lastName);
this.phone = phone;
this.membership = membership;
}
greeting(){
console.log(super.greeting())
return `Hello there ${this.firstName} ${this.lastName} ${this.phone}`
}
}
const john = new Customer('John','Doe','Standard');
console.log(john.greeting());
因此在类中我们可以使用 super 访问 Person.greeting 但以下不起作用
console.log(john.super.greeting());
那么,鉴于约翰,谁是客户,客户是人,有没有办法在课堂之外访问超级?
解决方法
Person.prototype
是 Customer.prototype
的原型。所以你可以像这样调用 Person.prototype.gretting
:
Customer.prototype.greeting = function() {
Object.getPrototypeOf(this.constructor.prototype).greeting.call(this);
}
顺便说一句,类使这变得容易多了:
class Customer extends Person {
greeting() {
super.greeting();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。