簡單的實現一個原型鏈

古墩古墩發表於2024-07-24

-

var a = { name: "a", age: 10, gender: "female" };
var b = {
  name: "b",
  age: 15,
  gender: "male",
  getGender() {
    return this.gender;
  },
};
var c = {
  name: "c",
  age: 20,
  getAge() {
    return this.age;
  },
};
var d = {
  getName() {
    return this.name;
  },
};
Object.setPrototypeOf(a, b); // 測試時可以用 a.__proto__ = b替代
Object.setPrototypeOf(b, c);
Object.setPrototypeOf(c, d);
Object.setPrototypeOf(d, null);
console.log(a.getName(), a.getAge(), a.getGender()); // a 10 female
console.log(b.getName(), b.getAge(), b.getGender()); // b 15 male
console.log(c.getName(), c.getAge()); // c 20

-

相關文章