gpt4 book ai didi

JavaScript 继承 Object.create()?

转载 作者:可可西里 更新时间:2023-11-01 01:26:34 25 4
gpt4 key购买 nike

如何使用 Object.create() 进行继承?我尝试了这些,但都没有用:

var B = function() {};
var A = function() {};
A = Object.create(B);
A.prototype.C = function() {};

var B = function() {};
var A = function() {};
A.prototype.C = function() {};
A = Object.create(B);

var B = function() {};
A = Object.create(B);
var A = function() {};
A.prototype.C = function() {};

没有任何效果。我应该如何使用这个新的 Object.create() 函数?

最佳答案

在 JavaScript 中有几种实现继承的方法

构造继承。在不需要调用父类(super class)型构造函数时使用:

function Rectangle(length, width) { 
this.length = length;
this.width = width;
}

Rectangle.prototype.getArea = function() {
return this.length * this.width;
};

// inherits from Rectangle
function Square(size) {
this.length = size;
this.width = size;
}

Square.prototype = Object.create(Rectangle.prototype);

var rect = new Rectangle(6, 8);
var square = new Square(10);

console.log(rect.getArea()); // 48
console.log(square.getArea()); // 100
console.log(rect instanceof Rectangle); // true
console.log(rect instanceof Object); // true
console.log(square instanceof Square); // true
console.log(square instanceof Rectangle); // true
console.log(square instanceof Object); // true

构造函数窃取。如果需要调用父类(super class)型构造函数时使用:

function Rectangle(length, width) { 
this.length = length;
this.width = width;
}

Rectangle.prototype.getArea = function() {
return this.length * this.width;
};

// inherits from Rectangle
function Square(size) {
Rectangle.call(this, size, size);
}

Square.prototype = Object.create(Rectangle.prototype);

var rect = new Rectangle(6, 8);
var square = new Square(10);

console.log(rect.getArea()); // 48
console.log(square.getArea()); // 100
console.log(rect instanceof Rectangle); // true
console.log(rect instanceof Object); // true
console.log(square instanceof Square); // true
console.log(square instanceof Rectangle); // true
console.log(square instanceof Object); // true

关于JavaScript 继承 Object.create()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3079887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com