this对象
1.this是什么
this是一个对象,在全局上下文中调用函数时,this指向windows。箭头函数中,箭头函数没有this指针,this指向windows。
this都有哪种使用场景呢?
主要由以下4点
- 作为构造函数执行
- 作为对象属性执行
- 作为普通函数执行
- call apply bind
2.如何判断this的值
1)对象调用,this指向该对象(谁调用了函数,this就指向谁)
var obj={ name:'aha', age:15, print:function(){ consol.log("this"+this); console.log("name"+this.name+"age"+this.age); } } obj.print(); //this[object Object] nameahaage15
2)直接调用函数,this指向全局
function foo(){ console.log(this); } foo();
输出:
3)通过new方式,this指向生成对象的实例(指向新对象),且值无法改变
function person(name,age){ person.name=name; person.age=age; console.log(this); } person('hah',15); var person2=new person('hah',15); // window //person {} [[Prototype]]: Object
3.如何改变这个值(this指向不同对象)
1)call
语法:fn1().call(obj,arguments)
2)apply
function print(){ console.log("name"+this.name); console.log(arguments); } var obj={ name:'aha', age:15, } print.call(obj,1,2,3)
// print.apply(obj,[1,2,3])
输出:

3)bind(需回调函数)
function print(){ console.log("name"+this.name); console.log(arguments); } var obj={ name:'aha', age:15, } var fn1=print.bind(obj,1,2,3); var fn2=print.bind(obj,[1,2,3]); fn1(); fn2();
输出:
4. call(),apply(),bind()三者的区别:
共同点:三者都可以改变this的值,第一个传递的参数都是this的对象;三者都采用后续传参的方式。
区别:call传递的参数是单向的(也可以是数组),而apply传递的是数组(单向会报错),bing没有规定,两者都可以;
call和apply是直接执行,而bind是先返回一个函数,需要调用这个函数才能执行。

浙公网安备 33010602011771号