在未經過綁定的this會指向Windows
使用Bind會return 一個function
let Dennis = {
name: "Dennis",
age: 22
}
function hello() {
console.log(this) //指向Window
console.log(this.age)
}
hello() //undefined
所以這邊使用bind method綁定在指定的物件身上
let Dennis = {
name: "Dennis",
age: 22
}
function hello() {
console.log(this) //指向Dennis
console.log(this.age) //22
}
const Hello = hello.bind(Dennis)
Hello()
使用call 會直接執行,所以不需要變數接住function再執行
let Dennis = {
name: "Dennis",
age: 22
}
function hello() {
console.log(this) //指向Dennis
console.log(this.age) //22
}
hello.call(Dennis)
並且 call可以傳入參數
let Dennis = {
name: "Dennis",
age: 22
}
function hello(parameter) {
console.log(`My name is ${this.name} phonenumber is ${parameter}`)
}
hello.call(Dennis,) //My name is Dennis phonenumber is undefined
加入參數
let Dennis = {
name: "Dennis",
age: 22
}
function hello(parameter) {
console.log(`My name is ${this.name} phonenumber is ${parameter}`)
}
hello.call(Dennis, "0900123123") //My name is Dennis phonenumber is 0900123123
apply跟call幾乎一樣,不同於傳入參數型態,若是array使用apply,string等等使用call
let c = ["000000"]
let Dennis = {
name: "Dennis",
age: 22
}
function hello(parameter) {
console.log(`My name is ${this.name} phonenumber is ${parameter}`)
}
hello.apply(Dennis, c) //My name is Dennis phonenumber is 000000