在 JavaScript 中,有几种方法可以实现继承:
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {}
Child.prototype = new Parent();
const child = new Child();
console.log(child.name); // 输出 'Parent'
child.sayHello(); // 输出 'Hello'
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {
Parent.call(this);
}
const child = new Child();
console.log(child.name); // 输出 'Parent'
child.sayHello(); // 报错:child.sayHello is not a function
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const child = new Child();
console.log(child.name); // 输出 'Parent'
child.sayHello(); // 输出 'Hello'
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {
Parent.call(this);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
const child = new Child();
console.log(child.name); // 输出 'Parent'
child.sayHello(); // 输出 'Hello'
这些都是常见的实现继承的方法,每种方法都有自己的优缺点,可以根据具体情况选择合适的方法。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:java实现多继承的方法有哪些