- call和apply的用途
- 改变this指向
先看个例子:
var obj1 = { name: 'sven' }; var obj2 = { name: 'anne' }; window.name = 'window'; var getName = function(){ alert(this.name); }; getName(); //输出:window getName.call(obj1); //输出:sven getName.call(obj2); //输出:anne
当执行getName.call(obj1)时,getName函数体内的this指向obj1对象
2.借用其他对象
var A = function(name){ this.name = name; ); var B = function(){ A.apply(this,arguments); }; B.prototype.getName =function(){ return this.name; }; var b = new B('sven'); console.log(b.getName()); //输出:seve