閱讀846 返回首頁    go 技術社區[雲棲]


深入分析js中的this、constructor 和prototype

this

this表示當前對象,如果在全局作用範圍內使用this,則指代當前頁麵對象window; 如果在函數中使用this,則this指代運行時此函數在什麼對象上被調用。 我們還可以使用apply和call兩個全局方法來改變函數中this的具體指向

先看一個在全局作用範圍內使用this的例子:

console.log(this === window); // true
console.log(window.alert === this.alert); // true
console.log(this.parseInt("021", 10)); // 21

函數中的this是在運行時決定的,而不是函數定義時,如下:

function foo() {   // 定義一個全局函數
    console.log(this.fruit);
}
var fruit = "apple";   // 定義一個全局變量,等價於window.fruit = "apple";此時函數foo中this指向window對象,這種調用方式和window.foo();是完全等價的    
foo(); // "apple"
var pack = {   // 自定義一個對象,並將此對象的屬性foo指向全局函數foo
    fruit: "orange",
    foo: foo
};
pack.foo(); // "orange"  此時函數foo中this指向window.pack對象

全局函數apply和call可以用來改變函數中this的指向

function foo() {   // 定義一個全局函數
    console.log(this.fruit);
}
var fruit = "apple";   // 定義一個全局變量
var pack = {   // 自定義一個對象
    fruit: "orange"
};
foo.apply(window);    // "apple"   等價於window.foo();
foo.apply(pack);  // "orange"   此時foo中的this === pack

注:apply和call兩個函數的作用相同,唯一的區別是兩個函數的參數定義不同

因為在JavaScript中函數也是對象,所以我們可以看到如下有趣的例子:

function foo() {   // 定義一個全局函數
    if (this === window) {
        console.log("this is window.");
    }
}
foo.boo = function() {   // 函數foo也是對象,所以可以定義foo的屬性boo為一個函數
    if (this === foo) {
        console.log("this is foo.");
    } else if (this === window) {
        console.log("this is window.");
    }
};
foo(); // this is window.   等價於window.foo();
foo.boo(); // this is foo.   可以看到函數中this的指向調用函數的對象
foo.boo.apply(window); // this is window.   使用apply改變函數中this的指向

prototype

prototype本質上還是一個JavaScript對象。並且每個函數都有一個默認的prototype屬性。 如果這個函數被用在創建自定義對象的場景中,我們稱這個函數為構造函數

隻有構造函數才有prototype屬性,而構造函數的實例是沒有該屬性的。在javascript中,每個函數都自動有一個prototype屬性,而不是每一個對象擁有prototype屬性

原型屬性與實例對象的創建與否沒有關係,它在對象創建之前就已經存在

function Person(name) {   // 構造函數
    this.name = name;
}
Person.prototype = {   // 定義Person的原型,原型中的屬性可以被自定義對象引用
    getName: function() {
        return this.name;
    }
}
var hao= new Person("haorooms");
console.log(hao.getName());     // "haorooms"

作為類比,我們考慮下JavaScript中的數據類型 - 字符串(String)、數字(Number)、數組(Array)、對象(Object)、日期(Date)等。我們有理由相信,在JavaScript內部這些類型都是作為構造函數來實現的

function Array() {   // 定義數組的構造函數,作為JavaScript的一種預定義類型
    // ...
}     
var arr1 = new Array(1, 56, 34, 12);   // 初始化數組的實例  
// 但是,我們更傾向於如下的語法定義:  
var arr2 = [1, 56, 34, 12];   

同時對數組操作的很多方法(比如concat、join、push)應該也是在prototype屬性中定義的。 實際上,JavaScript所有的固有數據類型都具有隻讀的prototype屬性 (這是可以理解的:因為如果修改了這些類型的prototype屬性,則那些預定義的方法就消失了), 但是我們可以向其中添加自己的擴展方法

Array.prototype.min = function() {   //向JS固有類型Array擴展一個獲取最小值的方法
    var min = this[0];
    for (var i = 1; i < this.length; i++) {
        if (this[i] < min) {
            min = this[i];
        }
    }
    return min;
};
console.log([1, 56, 34, 12].min()); // 1   // 在任意Array的實例上調用min方法

constructor

constructor始終指向創建當前對象的構造函數,返回對創建此對象的數組函數的引用

語法

object.constructor

舉例:

var arr = [1, 56, 34, 12];   // 等價於 var foo = new Array(1, 56, 34, 12);
console.log(arr.constructor === Array);    // true
var Foo = function() { };   // 等價於 var foo = new Function();
console.log(Foo.constructor === Function); // true
var obj = new Foo();   // 由構造函數實例化一個obj對象
console.log(obj.constructor === Foo);   // true
console.log(obj.constructor.constructor === Function); // true   // 將上麵兩段代碼合起來,就得到下麵的結論

但是當constructor遇到prototype時,有趣的事情就發生了。 我們知道每個函數都有一個默認的屬性prototype,而這個prototype的constructor默認指向這個函數

function Person(name) {
    this.name = name;
};
Person.prototype.getName = function() {
    return this.name;
};
var p = new Person("haorooms");
console.log(p.constructor === Person); // true
console.log(Person.prototype.constructor === Person); // true
// 將上兩行代碼合並就得到如下結果
console.log(p.constructor.prototype.constructor === Person); // true

當時當我們重新定義函數的prototype時(注意:和上例的區別,這裏不是修改而是覆蓋), constructor的行為就有點奇怪了

function Person(name) {
    this.name = name;
};
Person.prototype = {
    getName: function() {
        return this.name;
    }
};
var p = new Person("haorooms");
console.log(p.constructor === Person); // false
console.log(Person.prototype.constructor === Person); // false
console.log(p.constructor.prototype.constructor === Person); // false

為什麼呢? 原來是因為覆蓋Person.prototype時,等價於進行如下代碼操作:

Person.prototype = new Object({
    getName: function() {
        return this.name;
    }
});

而constructor始終指向創建自身的構造函數,所以此時Person.prototype.constructor === Object,即是:

function Person(name) {
    this.name = name;
};
Person.prototype = {
    getName: function() {
        return this.name;
    }
};
var p = new Person("haorooms");
console.log(p.constructor === Object); // true
console.log(Person.prototype.constructor === Object); // true
console.log(p.constructor.prototype.constructor === Object); // true

怎麼修正這種問題呢?方法也很簡單,重新覆蓋Person.prototype.constructor即可:

function Person(name) {
    this.name = name;
};
Person.prototype = {
    getName: function() {
        return this.name;
    }
};
Person.prototype.constructor = Person;
var p = new Person("haorooms");
console.log(p.constructor === Person); // true
console.log(Person.prototype.constructor === Person); // true
console.log(p.constructor.prototype.constructor === Person); // true

也可以這麼寫:

function Person(name) {
    this.name = name;
};
Person.prototype = {
    constructor:Person,//指定constructor
    getName: function() {
        return this.name;
    }
};

最後更新:2017-06-19 19:31:31

  上一篇:go  6月19日雲棲精選夜讀:血淚總結!創業公司CTO要避免哪些坑?
  下一篇:go  深度強化學習、GAN與多巴胺對撞:阿裏“AI 智能體”認知研討會幹貨