object.prototype.call
生活随笔
收集整理的這篇文章主要介紹了
object.prototype.call
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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");?
轉載于:https://www.cnblogs.com/alantao/p/5882411.html
總結
以上是生活随笔為你收集整理的object.prototype.call的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html给图片加文字,如何给图片加上字
- 下一篇: 4S店的大数据营销实战案例分析