1.new操作符
new会创造一个对象实例,这个实例继承了new操作符右边的对象,因此在调用方法时,this会指向对象实例
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">function A(){
this.user='Artimis'
}
var a=new A(); console.log(a.user) //Artimis => this指向a</pre>
2.call/apply/bind
call和apply主要用于指定this的环境变量,第一个参数是什么,this就指向什么,如果是null,则指向window
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">var a={
user:'Artimis',
fn:function(){
console.log(this.user)
}
}
var b=a.fn; b() //undefined
b.call(a) //Artimis => this指向a
b.call(null) //undefined => this指向window</pre>
bind是延迟的,会返回一个修改后的函数,可以自行决定执行的时间
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">var a={
user:'Artimis',
fn:function(){
console.log(this.user)
}
} var b=a.fn;
var c=b.bind(a)
c() //Artimis => 延迟执行,自定义执行时间</pre>
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">var a={
fn:function(x,y){
console.log(x+y)
}
} var b=a.fn;
var c=b.bind(a,2) //自定义参数x
c(3) //5</pre>