this绑定的四条规则 ; bind、call、apply的区别

版权声明:内容多为自言自语,请自行判断有无价值。 https://blog.csdn.net/weixin_41702247/article/details/82884003

this指向当前函数操作的对象

function foo(){
	console.log(this.a);
}
var obj1={
	a: 1,
	foo: foo
}

obj1.foo();		//1
//将上一句换为底下的,则会出现this对象丢失后使用默认绑定的情况
//回调函数丢失this对象很常见
var test=obj1.foo();
//此时obj1.foo指向的是不带任何修饰的foo函数调用,与obj1中的a没有联系
test;        //undefined

1.默认绑定:独立函数调用中的this指向全局对象,严格模式下声明的函数中,全局对象不可以作为this的默认绑定对象

2.隐式绑定:是否有上下文对象(被某个对象拥有或包含);需注意函数调用另作引用时,this对象丢失的情况

3.显示绑定:使用apply、call、bind对this对象进行强制绑定

var tom = {
    name : "Tom",
    say : function(age,gender) {
        console.log(this.name+age+gender);
    }
}
var mary = {
    name : "Mary",
}


tom.say(22,'male');                        //Tom22male
tom.say.call(mary,21,'female');            //Mary21female
tom.say.apply(mary,[21,'female']);         //Mary21female
tom.say.bind(mary,21,'female')();          //Mary21female


/*call(this需绑定的对象,参数);                 //参数挨个传入
apply(this需绑定的对象,[参数]);              //参数以数组形式传入
bind(this需绑定的对象,参数)();               //bind返回的是一个函数,需要()进行调用才有效果;call和apply是对函数的直接调用*/

4.new绑定:使用构造函数new实例化对象时,this指向新声明的对象

function Person(name){
	this.name=name;
	this.greet=function(){
		console.log('Hi, my name is '+this.name);
	}
}
var tom=new Person('Tom');
var mary=new Person('Mary');
tom.greet();         //Hi, my name is Tom
mary.greet();        //Hi, my name is Mary

猜你喜欢

转载自blog.csdn.net/weixin_41702247/article/details/82884003