K0II / JavaScript

Learning Logs
0 stars 0 forks source link

__proto__ 和 prototype #2

Open K0II opened 8 years ago

K0II commented 8 years ago


Object includes a prototype linkage feature that allows one object to inherit the properties of another.

基本上任何对象都有一个__proto__,并且都不为空,不能直接修改,而函数对象的prototype属性是可以修改的

[ ES5中是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.prototypeObject.create(o)创建的对象,生成的对象的__proto__绑定到o
JavaScript: The Good Parts,[ES5标准中已经可用]

Object.create = function (o) {
      var F = function () {};
      F.prototype = o;
      return new F();
};

var b=Object.create(a);


K0II commented 8 years ago

画了一叠图,终于搞懂了,从今天开始拥抱js的原型 !