object.prototype.call
/* * object.prototype.call * @ 当一个object没有某个方法,但是其他的有,我们可以借助call或apply用其它对象的方法来操作。 * @ 语法: fun.call(thisArg[, arg1[, arg2[, ...]]]) * @ param: thisArg {object} //当前引用对象 * @ 不传参数,传null,undefined, this指向window对象 * @ 传递另一个函数的函数名fun2, this指向函数fun2的引用 * @ 传递一个对象,函数中的this指向这个对象 * @ 值为原始值(数字,字符串,布尔值), this会指向该原始值的自动包装对象,如String,Number,Boolean * @ param: arg1, arg2, ... {object} // arguments参数 */
call函数中的this指向
function a(){ console.log(this); } function b(){} var objthis = {name: "Alan"}; //定义对象 a.call(); // window a.call(null); // window a.call(undefined); // window a.call(1); // Number {[[PrimitiveValue]]: 1} a.call(""); // String {length: 0, [[PrimitiveValue]]: ""} a.call(true); // Boolean {[[PrimitiveValue]]: true} a.call(b); // function b(){} a.call(objthis); // Object {name: "Alan"}
使用call对象的构造函数链
function Product(name, price){ this.name = name; this.price = price; if(price < 0){ throw RangeError('Cannot create product ' + this.name + ' with a negative price'); } } // call方法 function Food(name,price){ Product.call(this,name,price); this.category = "food"; } // 等同于 function Food(name,price){ this.name = name; this.price = price; if(price < 0){ throw RangeError('Cannot create product ' + this.name + ' with a negative price'); } this.category = "food"; }
使用call调用匿名函数
var animals = [ { species: "Lion", name: "king" }, { species: "Whale", name: "Fail" } ] for(var i = 0; i < animals.length; i++){ (function(i){ this.print = function(){ console.log("#" + i + " " + this.species + ": " + this.name); } this.print(); }).call(animals[i],i); // 等同于 /*(function(){ this.print = function(){ console.log("#" + i + " " + animals[i].species + ": " + animals[i].name); } this.print(); })();*/ }
使用call调用函数的上下文this
function greet(){ var reply = [this.person, "Is An Awesome", this.role].join(" "); console.log(reply); } var obj = { person: "Douglas Crockford", role: "Javascript Developer" }; greet.call(obj);
以DOM为例子
function changeStyle(attr, value){ this.style[attr] = value; } var box = document.getElementById('box'); window.changeStyle.call(box, "height", "200px"); window.changeStyle.apply(box, ['height', '200px']);
// 不用call
function say(name){ console.log(this + "," + name); } say.call2 = function( thisObj, arg1 ) { thisObj = new Object( thisObj ); thisObj.say = this; return thisObj.say(arg1); }; say.call2("hola","Mike");