Skip to content

call、apply和bind #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Twlig opened this issue Mar 9, 2022 · 0 comments
Open

call、apply和bind #28

Twlig opened this issue Mar 9, 2022 · 0 comments

Comments

@Twlig
Copy link
Owner

Twlig commented Mar 9, 2022

这三个函数都是为了改变调用函数的对象。也就是改变函数内部的this指向。

call

第一个参数是this要指向的新对象。后面的参数以参数列表的形式传递。call方法是立即调用

var o1 = {
    name: "lili",
    age: 20,
    func: function(country, city) {
        console.log("My name is " + this.name + ", I am " + this.age + " years old." + "I come from " + country + ", " + city)
    }
}
var o2 = {
    name: "zzy",
    age: 22
}
o1.func("USA", "NY"); //My name is lili, I am 20 years old.I come from USA, NY
o1.func.call(o2, "China", "NJ"); //My name is zzy, I am 22 years old.I come from China, NJ

apply

第一个参数是this要指向的新对象。后面的参数以数组的形式传递。apply方法是立即调用

o1.func("USA", "NY"); //My name is lili, I am 20 years old.I come from USA, NY
o1.func.apply(o2, ["China", "NJ"]); //My name is zzy, I am 22 years old.I come from China, NJ

bind

第一个参数是this要指向的新对象。后面的参数以参数列表的形式传递。bind方法是返回函数,不是立即调用。因此,要写一个()才能调用。

o1.func("USA", "NY"); //My name is lili, I am 20 years old.I come from USA, NY
o1.func.bind(o2, "China", "NJ")(); //My name is zzy, I am 22 years old.I come from China, NJ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant