object.prototype.call
2024-08-26 17:23:31
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");
最新文章
- 【GitHub Desktop】MacOS和Win下配置及简单的使用
- [ASP.NET MVC 小牛之路]14 - Unobtrusive Ajax
- Activity详解二 activity数据传递
- 双系统下(Ubuntu + win7)windows 无法连接无线网络
- 每天一个linux命令(28):tar命令
- 淘宝美工一站式:淘宝ps高级美工技巧视频教程,HTML代码学习【教程下载
- php pthreads 多线程扩展的使用:一个较为稳定例子。
- ORACLE EXPDP命令使用详细【转】
- oracle commit之后的数据回滚
- Uva11464 开关问题
- SpringMVC 配置
- 企业级分布式监控系统-Zabbix基础
- Javaweb学习笔记——(二十二)——————文件上传、下载、Javamail
- 6.1-uC/OS-III软件定时器
- Hadoop生态圈-Cloudera Manager的基本使用
- HDU 6298
- 【BZOJ】1002:轮状病毒(基尔霍夫矩阵【附公式推导】或打表)
- 利用 background 和 filter 模糊指定区域
- C# 对象不能从 DBNull 转换为其他类型。
- setPadding 与 setBackgroundDrawable