JavaScript Function.prototype.bind的用法是什么
Bind方法: 使用这个方法,我们可以将一个对象绑定到一个通用函数上,这样在需要时就会得到不同的结果。bind()方法接受一个对象作为参数并创建一个新函数。所以基本上bind函数返回函数。
让我们了解一下bind方法是何时使用的。
bind the object with common function
示例1:
Javascript
<script>
const gfg = {
name: "javascript",
content: "prototype",
feature: function () {
console.log(
`Help in learning {this.name}.
The topic is{this.content}`
);
}
}
// Simple method to feature of gfg object
gfg.feature();
console.log()
// Try to bind gfg object property feature
// to other common function so that it
// used for later use but it does not
// happen here
let b = gfg.feature;
b();
console.log()
// Now try to bind object using bind
// method
// bind method first argument refer
// object that's why parameter gfg object
let c = gfg.feature.bind(gfg);
c();
</script>

注意:将不同的对象绑定到一个公共函数,以便每个对象都可以访问该函数,并将额外的功能绑定到对象上,因此Bind函数接受任意数量的参数。
示例2:
Javascript
<script>
const gfg = {
name: "javascript",
content: "prototype",
}
const gfg1 = {
name: "c++",
content: "inheritance",
}
const gfg2 = {
name: "java",
content: "applet",
}
// Function which is binding with different object
function features(param) {
console.log(`Help in learning {this.name}.
The topic is{this.content} and
these are help in ${param}`)
}
// Binding obj1 abd extra functionality
let bindfunc = features.bind(gfg);
bindfunc("placement");
// Binding obj2
let bindfunc1 = features.bind(gfg2);
bindfunc1("placement");
</script>
极客教程