先来一句话总结下,谁调用这个this就是谁。下面是几个例子。
call 函数
function say(content) { console.log("From " + this + ": Hello "+ content); }
say.call("Bob", "World"); //==> From Bob: Hello World
这里的this指的就是Bob。
Step1: 把第二个到最后一个参数作为函数执行时要传入的参数
Step2: 把函数执行时的this指向第一个参数
Step3: 在上面这个特殊的上下文中执行函数
说白了,call 和 apply都是用来扩充函数的作用域。
function sum(num1, num2) {
return num1 + num2;
}
console.log(sum.call(window, 10, 10)); //20
console.log(sum.apply(window,[10,20])); //30
如果不这么搞,那么看下面:
window.firstName = "diz";
window.lastName = "song";
var myObject = { firstName: "my", lastName: "Object" };
function HelloName() {
console.log("Hello " + this.firstName + " " + this.lastName, " glad to meet you!");
}
HelloName(); //Hello diz song glad to meet you!
myObject.HelloName = HelloName;
myObject.HelloName(); //Hello my Object glad to meet you!
function hello(thing) {
console.log(this + " says hello " + thing);
}
person = { name: "caibirdme" }
person.hello = hello;
person.hello("world") // 相当于执行 person.hello.call(person, "world") //caibirdme says hello world hello("world") // 相当于执行 hello.call(window, "world") //[object DOMWindow]world
var obj = {
x: 20,
f: function(){
console.log(this.x);
} };
obj.f(); // obj.f.call(obj) //==> 20
obj.innerobj = {
x: 30,
f: function(){
console.log(this.x);
} }
obj.innerobj.f(); // obj.innerobj.f.call(obj.innerobj) // ==> 30
var x = 10;
var obj = {
x: 20, f: function(){
console.log(this.x); //this equals obj // ==> 20
var foo = function(){
console.log(this.x);
}
foo(); // foo.call(window) //foo中this被指定为window,所以==> 10 } }; obj.f(); // obj.f.call(obj) // ==> 20 10
var x = 10;
var obj = {
x: 20,
f: function(){
console.log(this.x);
var that = this; //使用that保留当前函数执行上下文的this
var foo = function(){ console.log(that.x); } //此时foo函数中的this仍然指向window,但我们使用that取得obj foo(); // foo.call(window) } };
obj.f();
obj.f.call(obj) // ==> 20 20
var x = 10;
var obj = {
x: 20,
f: function(){
console.log(this.x);
} };
obj.f(); // obj.f.call(obj) // ==> 20
var fOut = obj.f;
fOut(); // fOut.call(window) //==> 10
var obj2 = { x: 30, f: obj.f } obj2.f(); // obj2.f.call(obj2) //==> 30