Gre*_*een 58 javascript methods function this
我很感兴趣在JS中使用call()方法的原因是什么.它似乎重复了通常的调用方法this.
例如,我有一个call()代码.
var obj = {
objType: "Dog"
}
f = function(did_what, what) {
alert(this.objType + " " + did_what + " " + what);
}
f.call(obj, "ate", "food");
Run Code Online (Sandbox Code Playgroud)
输出是"狗吃食物".但是同样的结果我可以将函数分配给对象.
var obj = {
objType: "Dog"
}
f = function(did_what, what) {
alert(this.objType + " " + did_what + " " + what);
}
obj.a = f;
obj.a("ate", "food");
Run Code Online (Sandbox Code Playgroud)
结果是一样的.但这种方式更容易理解和使用.为什么需要call()?
Dav*_*ing 61
call当您想要控制将在调用的函数中使用的范围时使用.您可能希望this关键字不是您为该函数指定的范围,在这种情况下,您可以使用call或apply使用您自己的范围调用该函数.
F.ex,它还允许您在范围之外调用实用程序方法,例如使用"私有"函数时:
var obj = (function() {
var privateFn = function() {
alert(this.id);
}
return {
id: 123,
publicFn: function() {
privateFn.call(this);
}
};
}());
obj.publicFn();
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,privateFn未公开,obj但它仍然可以构造为好像它是公共范围的一部分(this以相同的方式使用).
Rob*_*cha 39
2017年更新
通过Function.prototype的所有函数都有.call方法.使用的原因.call()是指定变量" this"所指的内容.
MDN指定:
该
call()方法使用给定的此值和单独提供的参数调用函数.
考虑以下:
function x() {
return this;
}
x()
Run Code Online (Sandbox Code Playgroud)
在严格模式下,在非严格模式下x()返回undefined它Window在浏览器上下文中返回Global对象.
.call()我们告诉它的例子是什么" this"指的是:
function x() {
return this;
}
var obj = {
myName : 'Robert',
myLocation : 'Earth'
}
x.call(obj);
Run Code Online (Sandbox Code Playgroud)
结果:{myName: "Robert", myLocation: "Earth"}.在上面的例子中,我们将obj对象指定为this函数内部的值x()
它可以用于在OOP中模拟继承.
例:
var Robert = {
name: "Robert Rocha",
age: 12,
height: "5,1",
sex: "male",
describe: function() {
return "This is me " + this.name + " " + this.age + " " + this.height + " " + this.sex;
}
};
Run Code Online (Sandbox Code Playgroud)
让我们说上面是一个主对象(原型),你想继承describe另一个对象中的函数:
var Richard = {
name: "Richard Sash",
age: 25,
height: "6,4",
sex: "male",
}
Run Code Online (Sandbox Code Playgroud)
该Richard对象没有describe函数,您只想简单地继承该函数.你会这样做:
console.log( Robert.describe.call( Richard ) );
Run Code Online (Sandbox Code Playgroud)
输出: This is me Richard Sash 25 6,4 male
您可能会在示例中使用第二种方法,但有时您希望在另一个对象上使用一个对象的函数.一个例子是Array在像NodeLists 这样的类似对象的对象上使用方法
var el = document.getElementById("foo");
[].forEach.call(el.children, function(child, index) {
//Iterate over an element's children, performing an action on each one
});
Run Code Online (Sandbox Code Playgroud)
这与first class function的概念有关。基本上,像 Javascript 这样的语言允许您将函数视为自己的权利。函数可以存储在变量中或传递给其他函数。
call() 提供了一种执行不附加到任何其他对象的独立功能的方法。