JavaScript prototype背后的工作原理

首先从一个函数说起

function fn1(name, age) {

  this.name = name;
  this.age = age;

  this.say = function() {
    alert('my name:' + this.name + 'and age:'+ this.age);
    
   }

}

fn1.prototype.test = function() {
    alert('test');
}

var f1 = new fn1('jm',20);

f1.say(); //弹出 my name jm and age 20

f1.test(); //弹出test
这里发生什么事情?

一些其本的东西 我们要知道 每个函数(function)都有一个保留属性 prototype 它返回的是一个对象

这个对象可以写也可以读

每个函数new 出来的对象有一个隐式属性 (__proto_ = fn1.prototype)指向构造函数的原型的!

下面一个图说明prototype动行原理,(图中有参考网上一些资料):

posted @ 2015-04-16 10:38  KyrieYang  阅读(261)  评论(0编辑  收藏  举报