Skip to content
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

Js 给函数 Bind 对象 #61

Open
susouth opened this issue Dec 9, 2019 · 0 comments
Open

Js 给函数 Bind 对象 #61

susouth opened this issue Dec 9, 2019 · 0 comments
Labels
JavaScript 跟js相关的面试题 No.61

Comments

@susouth
Copy link
Contributor

susouth commented Dec 9, 2019

📚在线阅读:Js 给函数 Bind 对象 - No.61

我们常常需要将一个对象绑定到一个方法的 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

扩展阅读:

@susouth susouth added JavaScript 跟js相关的面试题 No.61 labels Dec 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript 跟js相关的面试题 No.61
Projects
None yet
Development

No branches or pull requests

1 participant