在 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'
这些都是常见的实现继承的方法,每种方法都有自己的优缺点,可以根据具体情况选择合适的方法。