简单的实现一个原型链
-
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
-