2.31-構造函數this指向

構造函數this指向:

1 構造函數this指的是對象實例

2 原型對象函數裏面也this也是指向實例對象

         // 構造函數
        function Student(name,age) {
            this.name = name;
            this.age = age;
        }

        Student.prototype = {
            constructor: Student, // 千萬別忘記
            study: function() {
                console.log(this);
                console.log('good good study');
            },
            run: function() {
                console.log('running');
            }
        }
        var zs = new Student('zs',18); // 實例對象
        var lisi = new Student('lisi',22);
        // 構造函數this指的是對象實例 Student{...}
        zs.study(); // 原型對象函數裏面也this也是指向實例對象

示例:擴展數組方法 Array

Array.prototype.getSum = function() {
    var sum = 0;
    // 原型對象函數裏面也this也是指向實例對象
    for (var i = 0; i < this.length; i++) {
           sum += this[i];
    }
    return sum;
}

var arr1 = [1, 2, 3]; //
var arr2 = [2, 4, 6, 8];
console.log(arr1.getSum());
console.log(arr2.getSum());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章