javascript 面向對象 new 關鍵字 原型鏈 構造函數

JavaScript面向對象
JavaScript 語言使用構造函數(constructor)作爲對象的模板。所謂”構造函數”,就是專門用來生成實例對象的函數。它就是對象的模板,描述實例對象的基本結構。一個構造函數,可以生成多個實例對象,這些實例對象都有相同的結構

  1. 構造函數的首字母大寫,區分一般函數。
  2. 函數體內部使用了this關鍵字,代表了所要生成的對象實例。
  3. 生成對象的時候,必須使用new命令。
  4. 構造函數內部使用嚴格模式 'use strict',防止當做一般函數調用,這樣就會報錯。
function Person(name, age, sex) {
    'use strict';
    this.name = name;
    this.age = age;
    this.sex = sex;
}

Person() 報錯
new Person("zhangxc", 29, "male");

1、new關鍵字 命令內部實現

function _new(constructor, params) { // 接受個數不確定參數,第一個參數:構造函數;第二個到第n個參數:構造函數傳遞的參數。
    // 1. 首先將參數組成一個數組 
    // 首先 .slice 這個方法在不接受任何參數的時候會返回 this 本身,這是一個 Array.prototype 下的方法,因此 this 就是指向調用 .slice 方法的數組本身。
    var args = Array.prototype.slice.call(arguments); // arguments僞數組,獲取函數的所有參數的僞數組。
    // 等價於
    // [].slice.call(arguments);
    // 2. 獲取構造函數
    var constructor = args.shift(); // shift()返回數組第一個元素
    // 3. 使用構造函數原型創建一個對象。我們希望以這個現有的對象作爲模板,生成新的實例對象,這時就可以使用Object.create()方法。
    var context = Object.create(constructor.prototype); // Object.create()參數是一個對象,新建的對象繼承參數對象的所有屬性
    // 4. 將參數屬性附加到對象上面
    var result = constructor.apply(context, args);
    // 5. 返回一個對象
    return (typeof result === 'object' && result != null) ? result : context;
}

function Person(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}

var args1 = _new(Person, "zhangxc", 18, "male");

// {name: "zhangxc", age: 18, sex: "male"}

var args2 = new Person("zhangxc", 18, "male");

// {name: "zhangxc", age: 18, sex: "male"}

new.target屬性

如果當前函數是new命令調用,new.target指向當前函數(構造函數的名稱),否則爲undefined。

function Test() {
  console.log(new.target === Test);
}

Test() // false
new Test() // true

2、this關鍵字
...
3、對象的繼承
... 待完善

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章