函数中this的指向
-
this是什么?
1)所有函数内部都有一个变量this;
2)this的值是调用函数的当前对象;
3)任何函数本质上都是通过某个对象来调用的,如果没有指定,那它就是直接指定window
-
如何确定this的值?
示例:test();//window
p.test();//p
new test(); //创建的对象,
p.call(obj)//obj
/*
this是什么?
如何确定this的值?
*/
function Person(color) {
console.log('1',this);
this.color = color;
this.getColor = function() {
console.log('2',this);
return this.color;
}
this.setColor = function(value) {
console.log('3',this);
this.color = value;
}
}
Person('red');// this是谁?,这里是执行Person方法,只会执行1,this打印window
var p = new Person('yelloe');//this是谁?这里生成一个对象实例,指挥执行1,this打印当前对象实例
p.getColor();//this是谁?这里执行2,this打印对象p
var obj = {};
p.setColor.call(obj,'black');//this是谁?这里执行3,this打印obj
var test = p.setColor;
test();//this是谁?这里执行3,this打印window
function fun1(){
function fun2 (){
console.log(this);
}
fun2()
}
fun1();//this打印window
函数中this的指向修改(apply,bind,call的区别)
- apply,bind,call这三个方法接收的参数形式不同,第一个参数都是指定的绑定对象obj,而apply第二个参数接收的是一个参数组成的数组,bing,call第二个参数开始,依次接收传入的参数;
- apply,call是立即调用函数,bind是将函数返回
var obj = {uesername:'kobe'};
function foo(data){
console.log(this,data);
}
// 传入的参数形式
//foo.apply(obj,[33,44,55]);
//foo.call(obj,33,44,55);
foo.bind(obj,33,44,55)();