【前端基础】JavaScript对象原型
每个实例对象都有一个私有属性__proto__,该属性指向它的构造函数的原型对象prototype。 该原型对象的__proto__也可以指向其他构造函数的prototype。
function Person(name) { this.name = name; this.setName = function(newName) { this.name = newName; }; } Person.prototype.getName = function() { return this.name; }; console.log(Person.prototype); /** * 输出 { getName: ƒ, constructor: ƒ } */ console.log(Person.__proto__); /** * 输出 { [native code] } */ const person = new Person('Tom'); console.log(person); /** * 输出 Person { name: 'Tom', setName: ƒ } */ console.log(person.__proto__); /** * 输出 Person { getName: ƒ, constructor: ƒ } */
function Man(name) { Person.call(this, name); this.isMale = true; } const man = new Man('LiLei'); console.log(man); /** * Man { name: 'LiLei', isMale: true, setName: ƒ } */ console.log(man.getName?.()); /** * undefined */ console.log(man.__proto__); /** * { constructor: ƒ } */
一个对象的__proto__指向它的构造函数的prototype。
Function.prototype.__proto__.constructor会指向Object。
最新的标准推荐使用Object.getPrototypeOf获取__proto__。