Open K0II opened 8 years ago
Object includes a prototype linkage feature that allows one object to inherit the properties of another.
基本上任何对象都有一个__proto__,并且都不为空,不能直接修改,而函数对象的prototype属性是可以修改的
__proto__
[ ES5中是Object.getPrototypeOf() ]
Object.getPrototypeOf()
var Person = function(name,age){ this.name = name || 'Down'; this.age = age || 18; } Person.prototype.say = function(){ console.log(this.age); } var person1 = new Person('John',10); person1.__proto__; // Object {} ==> Object.prototype console.log(person1.name, person1.age); // John 10 person1.say(); // 10 var person2 = new Person(); person2.say === person1.say; // true
var Person = { name: 'Down' || this.name, age: 18 || this.age } var person1 = Object.create(Person); person1.__proto__; // Object { name="Down", age=18} ==> Person console.log(person1.name, person1.age); // Down 18 person1.age = 30; console.log(person1.name, person1.age); // Down 30 var person2 = Object.create(Person); person1.name === person2.name; // true
new fn(),生成一个对象,对象的__proto__绑定到被调用的函数的fn.prototype上 Object.create(o)创建的对象,生成的对象的__proto__绑定到o上 JavaScript: The Good Parts,[ES5标准中已经可用]
new fn()
fn.prototype
Object.create(o)
o
Object.create = function (o) { var F = function () {}; F.prototype = o; return new F(); }; var b=Object.create(a);
画了一叠图,终于搞懂了,从今天开始拥抱js的原型 !
基本上任何对象都有一个
__proto__
,并且都不为空,不能直接修改,而函数对象的prototype属性是可以修改的[ ES5中是
Object.getPrototypeOf()
]new fn()
,生成一个对象,对象的__proto__
绑定到被调用的函数的fn.prototype
上Object.create(o)
创建的对象,生成的对象的__proto__
绑定到o
上JavaScript: The Good Parts,[ES5标准中已经可用]