原型链继承通过[[Prototype]]链接实现,子对象可访问父对象属性方法。使用Object.create()设置原型避免共享问题,constructor需手动修正。原型链顶端为Object.prototype,其[[Prototype]]为null。用hasOwnProperty()判断属性是否属于对象自身,防止原型链污染应避免修改内置原型,可用Object.create(null)或Object.freeze()。ES6 class底层仍基于原型链。
![js 原型链继承详解 - 探索对象间隐藏的 [[prototype]] 连接机制](https://img.php.cn/upload/article/001/253/068/175837680493018.png)
JS 原型链继承是通过对象间的
[[Prototype]]
解决方案
JavaScript 中,每个对象都有一个内部属性
[[Prototype]]
__proto__
Object.getPrototypeOf()
[[Prototype]]
null
原型链继承的核心在于设置构造函数的
prototype
new
[[Prototype]]
prototype
prototype
例如:
function Animal(name) {
this.name = name;
}
Animal.prototype.sayHello = function() {
console.log("Hello, I'm " + this.name);
};
function Dog(name, breed) {
Animal.call(this, name); // 调用父类构造函数,继承属性
this.breed = breed;
}
// 设置 Dog 的原型为 Animal 的实例
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // 修正 constructor 指向
Dog.prototype.bark = function() {
console.log("Woof!");
};
const myDog = new Dog("Buddy", "Golden Retriever");
myDog.sayHello(); // 输出 "Hello, I'm Buddy" (继承自 Animal)
myDog.bark(); // 输出 "Woof!" (Dog 自身的方法)
console.log(myDog instanceof Animal); // true
console.log(myDog instanceof Dog); // true这段代码首先定义了一个
Animal
prototype
sayHello
Dog
Animal.call(this, name)
Dog
Animal
name
关键的一步是
Dog.prototype = Object.create(Animal.prototype)
Object.create()
[[Prototype]]
Animal.prototype
Dog
Animal
prototype
Dog.prototype.constructor = Dog
constructor
Dog.prototype.constructor
Animal
最后,
myDog
Animal
Dog
为什么要使用 Object.create()
Dog.prototype = new Animal()
直接
Dog.prototype = new Animal()
Animal
Dog.prototype
Dog
Animal
Animal
Object.create(Animal.prototype)
[[Prototype]]
Animal.prototype
Animal
原型链的顶端是什么?如何判断一个对象是否具有某个属性?
原型链的顶端是
Object.prototype
Object.prototype
[[Prototype]]
null
Object.prototype
可以使用
hasOwnProperty()
const obj = { name: "Alice" };
console.log(obj.hasOwnProperty("name")); // true
console.log(obj.hasOwnProperty("toString")); // false (继承自 Object.prototype)hasOwnProperty()
true
false
如何避免原型链污染?
原型链污染指的是通过修改
Object.prototype
prototype
避免原型链污染的方法包括:
prototype
Object.prototype
Array.prototype
prototype
Object.create(null)
Object.create(null)
hasOwnProperty()
hasOwnProperty()
Object.freeze()
Object.freeze()
虽然原型链继承是 JavaScript 中实现继承的一种方式,但它也有一些局限性。随着 ES6 的引入,
class
以上就是JS 原型链继承详解 - 探索对象间隐藏的 [[Prototype]] 连接机制的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号