深刻分析js中的constructor 和prototype

在javascript的使用過程當中,constructor 和prototype這兩個概念是至關重要的,深刻的理解這兩個概念對理解js的一些核心概念很是的重要。javascript

咱們在定義函數的時候,函數定義的時候函數自己就會默認有一個prototype的屬性,而咱們若是用new 運算符來生成一個對象的時候就沒有prototype屬性。咱們來看一個例子,來講明這個html

function a(c){
    this.b = c;
    this.d =function(){
        alert(this.b);
    }
}
var obj = new a('test');
alert(typeof obj.prototype);//undefine
alert(typeof a.prototype);//object

  從上面的例子能夠看出函數的prototype 屬性又指向了一個對象,這個對象就是prototype對象,請看下圖java

a.prototype 包含了2個屬性,一個是constructor ,另一個是__proto__函數

這個constructor  就是咱們的構造函數a,這個也很容易理解。this

那麼__proto__ 是什麼呢?spa

這個就涉及到了原型鏈的概念:prototype

  每一個對象都會在其內部初始化一個屬性,就是__proto__,當咱們訪問一個對象的屬性 時,若是這個對象內部不存在這個屬性,那麼他就會去__proto__裏找這個屬性,這個__proto__又會有本身的__proto__,因而就這樣 一直找下去。3d

請看mozzlia 對它對它的描述code

When an object is created, its __proto__ property is set to constructing function's prototype property. For example var fred = new Employee(); will cause fred.__proto__ = Employee.prototype;.htm

This is used at runtime to look up properties which are not declared in the object directly. E.g. when fred.doSomething() is executed and fred does not contain adoSomethingfred.__proto__ is checked, which points to Employee.prototype, which contains a doSomething, i.e. fred.__proto__.doSomething() is invoked.

Note that __proto__ is a property of the instances, whereas prototype is a property of their constructor functions.

無論你信不信,咱們來看圖

在後面若是加上 alert(obj.__proto__ === a.prototype) //true

同理,在這裏咱們來分析出new 運算符作了那些事情

  1.  var obj={}; 也就是說,初始化一個對象obj。
  2. obj.__proto__=a.prototype;
  3.  a.call(obj);也就是說構造obj,也能夠稱之爲初始化obj。

咱們將這個例子改造一些,變得複雜一點。

function a(c){
    this.b = c;
    this.d =function(){
        alert(this.b);
    }
}
a.prototype.test = function(){
    alert(this.b);
}
var obj = function (){}
obj.prototype = new a('test');
obj.prototype.test1 =function(){
    alert(22222);
}
var t = new obj('test');
t.test();//alert('test');

咱們來分析下這個過程

由 var t = new obj('test'); 咱們能夠獲得 t.__proto__ = obj.prototype,可是上面指定obj.prototype =new a('test'); 能夠這樣來看下

obj.prototype = p, p = new a('test'); p.__proto__ = a.prototype; 

那麼obj.prototype.__proto__ = a.prototype,由 t.__proto__ = obj.prototype 能夠得出 t.__proto__.__proto__ = a.prototype,

因此對象t先去找自己是的prototype 是否有test函數,發現沒有,結果再往上級找,即 t.__proto__   ,亦即obj.prototype 尋找test函數 ,可是obj.prototype 也沒有這個函數,而後再往上找。即

 t.__proto__.__proto__ 找,因爲t.__proto__.__proto__ = a.prototype  在 a.prototype  中找到了這個方法,輸出了alert('test')

從這裏能夠分析得出一個結論,js中原形鏈的本質在於 __proto__ 

再看看一個列子

function a(c){
    this.b = c;
    this.d =function(){
        alert(this.b);
    }
}
var obj  = new a('test');
alert(obj.constructor);//function a(){}
alert(a.prototype.constructor);//function a(){}

根據上面講到的__proto__ 咱們來分析下,首先obj是沒有constructor 這個屬性的,可是 obj.__proto__ = a.prototype;就從

a.prototype中尋找,而 a.prototype.constructor 是就a,全部二者的結果是一同樣的.

 

文章轉載自:http://www.cnblogs.com/yupeng/archive/2012/04/06/2435386.html

相關文章
相關標籤/搜索