gpt4 book ai didi

Javascript OOP 继承

转载 作者:行者123 更新时间:2023-11-29 21:32:07 25 4
gpt4 key购买 nike

我创建了这些对象及其方法。

var Door = function(no = 10) {
this.number = isNaN(no) ? 10 : no;
}

var Room = function(door) {
this.door = door instanceof Door ? door : new Door();
this.name = 'Room';
}

function MyRoom(){
this.name = 'MyRoom';
}
MyRoom.prototype = new Room();

function HerRoom() {
this.name = 'HerRoom';
}
HerRoom.prototype = new Room();

var $myDoor = new Door(10);
var $herDoor = new Door(5);

var $myRoom = new MyRoom($myDoor);
var $herRoom = new HerRoom($herDoor);

console.log($myDoor, $myRoom.door);
// $myDoor.number is 10
// $myRoom.door.number is 10

console.log($herDoor, $herRoom.door);
// $herDoor.number is 5
// $herRoom.door.number is 10

我想知道我做错了什么导致 $myDoor == $myRoom.door, BUT, $herDoor != $herRoom.door。谁能帮我看看我的错误在哪里?

更新:

因为,我创造

var $herDoor = new Door(5);
var $herRoom = new HerRoom($herDoor);

我期望 $herRoom.door.number 等于 $herDoor.number。因为,

$herDoor instanceof Door // true;

最佳答案

I am wondering what I did wrong that makes $myDoor == $myRoom.door, BUT, $herDoor != $herRoom.door.

只是因为你在初始化 $herDoor 时给了 var $herDoor = new Door(5);5 分配给了 number 属性。

更改构造函数调用中的值将为您提供所需的输出

var $herDoor = new Door(10);

抱歉编辑晚了,您似乎希望在将 Room 的原型(prototype)分配给 MyRoom 之后,调用 Room 的构造函数。此外,由于您没有将门对象传递给 MyRoom,它永远不会得到这个对象。

您需要进行以下更改

function Door (no) {
this.number = isNaN(no) ? 10 : no;
}

function Room (door) {
this.door = door instanceof Door ? door : new Door();
this.name = 'Room';
}

function MyRoom(door){
this.name = 'MyRoom'; Room.call(this, door); //door object is passed and Room constructor is invoked with it
}
MyRoom.prototype = Object.create(Room.prototype);
function HerRoom(door) {
this.name = 'HerRoom'; Room.call(this, door);//door object is passed and Room constructor is invoked with it
}
HerRoom.prototype = Object.create(Room.prototype);

var $myDoor = new Door(10);
var $herDoor = new Door(5);

var $myRoom = new MyRoom($myDoor);
var $herRoom = new HerRoom($herDoor);

console.log($myDoor, $myRoom.door);
console.log($herDoor, $herRoom.door);

关于Javascript OOP 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35917224/

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