js the new call apply bind JSON.stringify principle and simulation to achieve

 The principle and 1.new

  • It creates a new object.

  • It will be executed  (ie  ) link.[[Prototype]]__proto__

  • It makes  thispoint to the newly created object.

  • By  newevery object created will eventually be  linked to the function of  the object.[[Prototype]]prototype

  • If the function does not return the object type  Object(included  ), then the  function call expression will return the object reference.Functoin,Array,Date,RegExg,Errornew

   A function = var (X, Y) { 
        in this.x = X; 
        this.y from = Y; 
        this.add = function () { 
            the console.log (+ this.y from in this.x) 
        } 
    } 
    A.prototype.sayHello = function () { 
        ( '! Hello') the console.log 
    } 

    function New (FUNC) { 
        var RES = {} 
        IF (! func.prototype == null) { 
            RES = .__ proto__ func.prototype; 
        } 
        // Array.prototype .slice.call (arguments, 1) is to obtain parameter arguments [0] is not removed func         // more argument for more explanation see this: https://developer.mozilla.org/zh-CN/docs/Web/ JavaScript / Reference / Functions / arguments
        

// use apply because the results do not call Array.prototype.slice.call (arguments, 1) is an array.
// perform a func reason is to make A performs the initialization function is simply to assign xy add
var RET = func.apply (RES, Array.prototype.slice.call (arguments,. 1));
     IF ((typeof RET ! === 'Object' || typeof RET === 'function') && RET == null) { return RET; } the else { return RES; } } var obj = New (A,. 1, 2) // or var obj = new A (1,2)

The principle and 2.JSON.stringify

  • Boolean|Number|String Type is automatically converted to the corresponding original value.

  • undefined, And any function  symbol, will be ignored (non-array properties appears when the value of the object), or is converted into  null(occur in an array).

  • Non-enumerable properties will be ignored

     When used with the usual JSON.parse (JSON.stringify (obj)) to achieve the depth of cloning, value is  undefined, functions, and symbol的 key 都会消失,原因就是上面第二条

 

    // array for the case where the element is not done the processing, may be of interest to try their 
    function json2str (O) { 
        the let ARR = []; 
        const FMT = function (S) { 
            IF (typeof S == 'Object' && ! S == null) { 
                return json2str (S); 
            } 
            // Symbol undefine function when set to null, a distinction '' and `" $ {s} "` , which is more "" is not a true null 
            IF (S === null) { 
                return null 
            } the else IF (S === to false) { 
                return to false 
            } the else IF (/ ^ (undefined | Symbol |. function) $ / Test (typeof S)) { 
                return '' 
            the else {} 
                return `" $ {S} "`
            }
        }
        for (var I in O) {   Results the following two printing // is the same
            // if it is empty it is representative of undefine symbol function would not have removed 
            if (fmt (o [i] ) === null || fmt (o [i]) === false || fmt (o [i] )) { 
                arr.push ( `" $ {I} ": $ {FMT (O [I])}`) 
            } 
        } 
        return $ `{{arr.join ( ',')}}` 
    } 

    var {obj = 
        name: 'Tangbo Long', 
        Age: '20 is', 
        MSG: { 
            title: '11 ', 
            face: '22' 
        }, 
        A: function FUNC () {Alert ( '. 1')}, 
        B: to false, 
        C: null , 
        D: undefined, E: the Symbol (), 
        E: '' 
    } 
the console.log (the JSON.stringify (obj)) console.log(json2str(obj))
console.log and ((obj) JSON.stringify) results console.log (json2str (obj)) as follows, exactly the same:

3.call apply the principle and

A more detailed explanation see here  https://www.jianshu.com/p/af3f41d8ef99

callgrammar:

fun.call(thisArg,arg1,arg2,...), A function call, this having a specified value and the parameters (parameter list) separately provided.

applygrammar:

func.apply(thisArg,[argsArray]), A function call, as well as an array (or a similar array of objects) parameters provided.

call code is implemented as follows:

    Function.prototype.call2 = function (context) {
        var context = context || window; // 当context是null 的时候 this 指向window
        context.fn = this;

        var args = [...arguments].slice(1);

        var result = context.fn(args);

        delete context.fn
        return result;
    }

    // 测试一下
    var value = 2;

    var obj = {
        value: 1
    }

    function bar(name, age) {
        console.log(this.value);
        return {
            value: this.value,
            name: name,
            age: age
        }
    }

    bar.call (null); // this is null when the incoming point window, the output 2 

    the console.log (bar.call2 (obj, 'Cherry', 18 is));

apply the code to achieve the following (in fact passed into a second parameter array):

    Function.prototype.call2 = function (context, arr) {
        var context = context || window; // 当context是null 的时候 this 指向window
        context.fn = this;
        var result = ''
        if(!arr) {
            result = context.fn()
        } else {
            var args = []; 
            for(var i = 0; i < arr.length; i++) {
                 args.push('arr[' + i + ']');
             } 
             result =  eval('obj.fn('+args+')');
        }
        delete context.fn
        return result;
    }

    // 测试一下
    var value = 2;

    var obj = {
        value: 1
    }

    function bar(name, age) {
        console.log(this.value);
        return {
            value: this.value,
            name: name,
            age: age
        }
    }

    bar.call(null); // 当传入null的时候 this指向window, 

    console.log(bar.call2(obj, ['Cherry', 18]));

The principle and 4.bind

A more detailed explanation see here:  https://blog.csdn.net/daimomo000/article/details/72897035

bind()method:

It creates a new function. When this new function is called, the bind () of this first parameter as it runs, and after a sequence parameter will be passed as an argument in the argument at the front. (From MDN)

    Function.prototype.bind2 = function (context) {

        if (typeof this !== "function") {
          throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
        }

        var self = this;
        var args = Array.prototype.slice.call(arguments, 1);
        var fNOP = function () {};

        var fbound = function () {
            self.apply(this instanceof self ? this : context, args.concat(Array.prototype.slice.call(arguments)));
        }

        fNOP.prototype = this.prototype;
        fbound.prototype = new fNOP();

        return fbound;

    }

 

 

 

Guess you like

Origin www.cnblogs.com/yalong/p/11209939.html