500   JS

一,call 方法主要用于改变函数内部 this 的指向
var p = {
    word: 'p',
	say: function(i) {
		console.log(i)
		console.log(this.word)
	}
};
var g = {
	word:'g'
};
p.say('hello');
p.say.call(g,'hello');

 

二,apply 也能达到 call 方法
p.say.apply(g,['hello']);

apply 和 call 不同主要是传递参数格式不一样,call 是一个个传递,apply 是通过 arguments,为了兼容不同参数个数,采用 apply 更合适

var p = {
    word: 'p',
	say: function(i,j,k) {
		console.log(i,j,k)
		console.log(this.word)
	}
};
var g = {
	word:'g'
};

p.say.call(g,'one','two','three');
p.say.apply(g,['one','two','three']);

 

 

三,ES5 中增加了 bind 的方法,功能跟 call 和 apply 改变函数内部的 this 指向,参数跟 call 一样
var p = {
    word: 'p',
	say: function(i,j,k) {
		console.log(i,j,k)
		console.log(this.word)
	}
};
var g = {
	word:'g'
};

var b = p.say.bind(g,'one','two','three');
b();

从上述例子可以看出,bind 跟 call 和 apply 主要区别是返回一个函数,而不是立即执行




Leave a Reply

Your email address will not be published. Required fields are marked *