原型链 及 属性问题

原型链

  1. 原型链(图解)

    • 拜访一个对象的属性时,

      • 先在本身属性中查找,找到返回
      • 如果没有,再沿着__proto__这条链向上查找,找到返回
      • 如果最终没找到,返回undefined
    • 别名:隐式原型链
    • 作用:查找对象的属性(办法)
  2. 构造函数/原型/实体对象的关系(图解)
  3. 构造函数/原型/实体对象的关系(图解)

     function Fn(){     this.test1=function(){         console.log('test1()')     } } Fn.prototype.test2=function(){     console.log('test2()') } var fn = new Fun() fn.test1() fn.test2() console.log(fn.toString()) fn.test3()

  4. 函数的显示原型指向的对象:默认是空的Object实例对象(但Object不满足)

     console.log(Fn.prototype instanceof Object)        //true console.log(Object.prototype instanceof Object)        //false console.log(Function.prototype instanceof Object)    //true
  5. 所有函数都是Function的实例(蕴含Function)

     console.log(Function.__proto__===Function.prototype)    //true
  6. Objec的原型对象是原型链止境

     console.log(Object.prototype.__proto__)        //null

属性问题

  1. 读取对象的属性值时:会主动到原型链中查找
  2. 设置对象的属性值时:不会查找原型链,如果以后对象中没有此属性,间接增加此属性并设置其值
  3. 办法个别定义在原型中,属性个别通过构造函数定义在对象自身上

     function Fn(){ } Fn.prototype.a = 'xxx' var fn1 = new Fn() console.log(fn1.a) var fn2 = new Fn() fn2.a = 'yyy' console.log(fn1.a)

属性放本身,办法放原型

function Person(name,age){    this.name = name    this.age = age}Person.prototype.setName = function(name){    this.name = name}var p1 = new Person('Tom',12)p1.setName('Bob')console.log(p1)                                //Bob 12    var p2 = new Person('jack',12)p2.setName('Cat')console.log(p2)                                //Cat 12console.log(p1.__proto__===p2.__proto__)       //true