简体   繁体   中英

Javascript OOP inheritance

I created these objects and their methods.

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

I am wondering what I did wrong that makes $myDoor == $myRoom.door , BUT , $herDoor != $herRoom.door . Can anyone please help me to notice where my mistake is?

Update:

Since, I create

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

I am expecting that $herRoom.door.number is equal to $herDoor.number . Since,

$herDoor instanceof Door // true;

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

Simply because you gave var $herDoor = new Door(5); while initializing $herDoor which assigned 5 to number property.

Changing the value in constructor call will give you the output you want

var $herDoor = new Door(10);

Apologies for late edit, it seems that you are hoping that after assigning the prototype of Room to MyRoom, Room's constructor will be invoked. Also, since you are not passing door object to the MyRoom, it will never get this object.

You need to make following changes

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM