给函数 Bind 对象
我们常常需要将一个对象绑定到一个方法的 this
上。在 JS 中,如果你想要调用一个函数并指定它的 this
时可以使用 bind
方法。
Bind 语法
fun.bind(thisArg[, arg1[, arg2[, ...]]])
参数
thisArg
当绑定函数被调用时,该参数会作为原函数运行时的 this 指向。
arg1, arg2, …
当绑定函数被调用时,这些参数将置于实参之前传递给被绑定的方法。
返回值
返回由指定的this值和初始化参数改造的原函数拷贝
JS 中的实例
const myCar = {
brand: 'Ford',
type: 'Sedan',
color: 'Red'
};
const getBrand = function () {
console.log(this.brand);
};
const getType = function () {
console.log(this.type);
};
const getColor = function () {
console.log(this.color);
};
getBrand(); // object not bind,undefined
getBrand(myCar); // object not bind,undefined
getType.bind(myCar)(); // Sedan
let boundGetColor = getColor.bind(myCar);
boundGetColor(); // Red
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW