Object.prototype.foo = 'Object'; Function.prototype.foo = 'Function'; function A

92 阅读1分钟

每个构造函数拥有__prop__和prototype属性,__prop__是原型链查询时实际可以查到的,它指向构造函数的原型对象;而prototype是函数独有的,它包含所有实例共享的属性和方法,因此实例化的对象会指向它,

Animal为构造函数,实际指向的是__prop__,即Function.prototype,因此Animal.foo即Function.prototype.foo='Function'

cat是Animal实例化出来的,因此他们的__proto__指向的是Animal的原型对象,即cat.foo = Object.prototype.foo

发表于 2022-02-19 22:20:27回复(0)

2

Object.prototype.foo = ``'Object'``;

Function.prototype.foo = ``'Function'``;

function Animal () {};

var cat = ``new Animal();

console.log(cat.foo);

console.log(Animal.foo);

构造函数Animal是由 new Function() 创建的一个对象,因此Animal的__proto__属性指向的是Function.prototype;又因函数本身又是一个对象,因此Animal.prototype是指向Object.prototype;cat是由Animal创建出来的实例,cat.__proto__指向Animal.prototype.