js-new、object.create、bind的模擬實現【轉載備忘】

//建立Person構造函數,參數爲name,age
function Person(name,age){
    this.name = name;
    this.age = age;
}
 
function _new(){
    //1.拿到傳入的參數中的第一個參數,即構造函數名Func
    var Func = [].shift.call(arguments);
    //2.建立一個空對象obj,並讓其繼承Func.prototype
    var obj = Object.create(Func.prototype);
    //3.執行構造函數,並將this指向建立的空對象obj
    Func.apply(obj,arguments)
    //4.返回建立的對象obj
    return obj
}
 
 
xm = _new(Person,'xiaoming',18);
 
console.log(xm);

來源https://blog.csdn.net/u010342862/article/details/80016695app

 

if (typeof Object.create !== "function") {
    Object.create = function (proto, propertiesObject) {
        if (typeof proto !== 'object' && typeof proto !== 'function') {
            throw new TypeError('Object prototype may only be an Object: ' + proto);
        } else if (proto === null) {
            throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument.");
        }

        if (typeof propertiesObject != 'undefined') throw new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument.");

        function F() {}
        F.prototype = proto;

        return new F();
    };
}

來源https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill函數

 

if (!Function.prototype.bind) {
  Function.prototype.bind = function(oThis) {
    if (typeof this !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var aArgs   = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP    = function() {},
        fBound  = function() {
          // this instanceof fNOP === true時,說明返回的fBound被當作new的構造函數調用
          return fToBind.apply(this instanceof fNOP
                 ? this
                 : oThis,
                 // 獲取調用時(fBound)的傳參.bind 返回的函數入參每每是這麼傳遞的
                 aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    // 維護原型關係
    if (this.prototype) {
      // Function.prototype doesn't have a prototype property
      fNOP.prototype = this.prototype; 
    }
    // 下行的代碼使fBound.prototype是fNOP的實例,所以
    // 返回的fBound若做爲new的構造函數,new生成的新對象做爲this傳入fBound,新對象的__proto__就是fNOP的實例
    fBound.prototype = new fNOP();

    return fBound;
  };
}

來源https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bindthis

相關文章
相關標籤/搜索