Apply/Call Javascript 中的方法:第一个参数是什么 "this"?
Apply/Call method in Javascript: What is the first arguments "this"?
我对正确使用 apply 或 call 方法感到困惑。
我知道 apply 将数组传递给函数,而 call 将字符串传递给函数。
例如下面的代码,"this"与代码有什么关系?如果它与这段代码无关,那么谁能给我一个 "this" 正确实施的例子?
function myFunction(a, b) {
return a * b;
}
myArray = [10,2];
myFunction.apply(this, myArray);
this
是Apply/Call
函数的范围。一个例子是:
function test() {
alert(this.a);
}
(function () {
this.a = "test";
test();//test
var self = this;
(function () {
this.a = "Foo";
test();//Foo
test.apply(self, []);//test
}());
}());
第一个参数将是函数中的 this
。
即:
var p = {"name":"someone"};
function myFunction(a, b) {
console.log(this);
return a*b;
}
var myArray = [10,2];
myFunction.apply(p, myArray); //log output shows {"name":"someone"}
这是函数的上下文。如果函数内部有 this.something,它将从该上下文对象访问特定的 属性。
function foo(bar) {
this.bar = bar;
}
foo.apply(this, ['Hello']); //calling foo using window as context (this = window in global context in browser)
console.log(this.bar); //as you can see window.bar is the same as this.bar
console.log(window.bar);
var ctx = {}; //create a new context
foo.apply(ctx, ['Good night']);
console.log(ctx.bar); //ctx now has bar property that is injected from foo function
Open up your dev console to see result.
参见:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
我对正确使用 apply 或 call 方法感到困惑。 我知道 apply 将数组传递给函数,而 call 将字符串传递给函数。 例如下面的代码,"this"与代码有什么关系?如果它与这段代码无关,那么谁能给我一个 "this" 正确实施的例子?
function myFunction(a, b) {
return a * b;
}
myArray = [10,2];
myFunction.apply(this, myArray);
this
是Apply/Call
函数的范围。一个例子是:
function test() {
alert(this.a);
}
(function () {
this.a = "test";
test();//test
var self = this;
(function () {
this.a = "Foo";
test();//Foo
test.apply(self, []);//test
}());
}());
第一个参数将是函数中的 this
。
即:
var p = {"name":"someone"};
function myFunction(a, b) {
console.log(this);
return a*b;
}
var myArray = [10,2];
myFunction.apply(p, myArray); //log output shows {"name":"someone"}
这是函数的上下文。如果函数内部有 this.something,它将从该上下文对象访问特定的 属性。
function foo(bar) {
this.bar = bar;
}
foo.apply(this, ['Hello']); //calling foo using window as context (this = window in global context in browser)
console.log(this.bar); //as you can see window.bar is the same as this.bar
console.log(window.bar);
var ctx = {}; //create a new context
foo.apply(ctx, ['Good night']);
console.log(ctx.bar); //ctx now has bar property that is injected from foo function
Open up your dev console to see result.
参见:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply