兩中方法都能改變this指向,很類似,區別主要是第二個以後引數,
用法:a.call(b,1,2); 表示要把a函式的this指向修改為b的this指向,並且執行a函式,傳進去的引數是(1,2)
//function
say(arg1,arg2);
var obj =
}say.call(obj,'one','two');//
tom one two
say.spply(obj,['one','two']);//
tom one two 效果一樣
2.bind()
作用:bind()方法會建立一個新函式,稱為繫結函式,當呼叫這個繫結函式時,繫結函式會以建立它時傳入 bind()方法的第一個引數作為 this,傳入 bind() 方法的第二個以及以後的引數加上繫結函式執行時本身的引數按照順序作為原函式的引數來呼叫原函式。
用法:
var foo =.bind(this));//這裡的this是eventbind的this,即指向的是foo
}}
注意:多次bind無效,按第一次算
總結一下
3.new
new執行原理是:
new animal('cat') = ;//先定義一個空物件
obj.__proto__ = animal.prototype;//
把 obj 的__proto__ 指向建構函式 animal 的原型物件 prototype,此時便建立了 obj 物件的原型鏈:obj->animal.prototype->object.prototype->null
var result = animal.call(obj,"cat");//
改變this指向,從animal改變到obj上
return
typeof result === 'object'? result : obj; //
返回}
用法:
functionfn()
var a = new fn();//
this指向a
console.log(a.user); //
追夢子
4.return
在建構函式的時候,使用return進行返回一個object的時候,當去new一個例項物件的時候,會將this指向改變為return的object;
用法:
functionfn()
; }
var a = new
fn;
console.log(a.user);
//111