(笔记)JS之call,apply,bind,new模拟实现

109 阅读1分钟

call模拟实现

A.call(B, arguments)

var A = {
    name: '1',
    getName: function(name) {
    	console.log(name)
    }
};

var B = {
	name: '2',
};

Function.prototype.newCall = function(ctx) {
	var o = {};
    ctx.getName = this; // 由于是A.getName调用newCall方法,所有this指向A
    const param = [...arguments].splice(1);
    ctx.getName(param)
    delete ctx.getName;
}

A.getName.newCall(B, [1, 2, 3])

bind实现

A.getName.bind(B)

var A = {
    name: '1',
    getName: function(name) {
    	console.log(this.name)
    }
};

var B = {
	name: '2',
};

Function.prototype.newBind = function(ctx) {
	var ctx = ctx || window;
    var params = [...arguments].splice(1);

    return function() {
    	this.apply(ctx, params)
    }
}

new实现

function Person(name) {
	this.age = '21',
    this.name = name;
    this.say = function() {
    	console.log('my name is' + this.name + 'and age is' + this.age)
    }
}

function _new(ctx) {
	var o = {};
    o._proto_ = ctx.prototype;
    const params = [...arguments].slice(1);
    ctx.apply(o, params);
    return o;
}

var p = _new(Person, 'jeck');