gpt4 book ai didi

javascript属性值函数不被继承

转载 作者:行者123 更新时间:2023-11-28 01:42:11 25 4
gpt4 key购买 nike

“SquareFactory”创建的对象从 ShapeFactory 创建的对象继承“x、y、宽度和高度”值,但不继承函数 right()。我假设这条线

 square.protoype = ShapeFactory();

创建要搜索的属性的链接。但这似乎并没有发生。我是否遗漏了一些关于原型(prototype)的信息?我读过How does JavaScript .prototype work?但以我目前对原型(prototype)的理解无法找到错误。

function ShapeFactory() {
return {
x: 0,
y: 0,
width: 0,
height: 0,
right: function () {
return this.x + this.width;
}
};
}
function SquareFactory() {
var square = {
insideBoundary: function (x, y) { // this function works
return (x > this.x && x < (this.x + this.width)
&& y > this.y && y < (this.y + this.height));
},
print_info: function () { // this function throws error
console.log(this.x + " " + this.y + " "
+ this.width + " " + this.height
+ this.right() + " " + this.bottom()); // error accessing right() fn
}
};
square.protoype = ShapeFactory();
return square;
}

最佳答案

这是一个工作示例:

function ShapeFactory() {
this.x = 0;
this.y = 0;
this.width = 0;
this.height = 0;
}

ShapeFactory.prototype.right = function () {
return this.x + this.width;
};

function SquareFactory() {
ShapeFactory.call(this);
}

SquareFactory.prototype = Object.create(ShapeFactory.prototype);

SquareFactory.prototype.insideBoundary = function (x, y) {
return (x > this.x && x < (this.x + this.width) && y > this.y && y < (this.y + this.height));
};

SquareFactory.prototype.print_info = function () {
console.log(this.x + " " + this.y + " " + this.width + " " + this.height + this.right());
};

var shapeFactory = new ShapeFactory();
var squareFactory = new SquareFactory();

console.log(ShapeFactory.prototype.right === SquareFactory.prototype.right); // ShapeFactory and SquareFactory are sharing the same right function

console.log(squareFactory instanceof SquareFactory); // squareFactory is a SquareFactory
console.log(squareFactory instanceof ShapeFactory); // squareFactory is also a ShapeFactory
console.log(shapeFactory instanceof SquareFactory); // shapeFactory is not a SquareFactory
console.log(shapeFactory instanceof ShapeFactory); // shapeFactory is a ShapeFactory

squareFactory.print_info();

关于javascript属性值函数不被继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20791289/

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