bind()
方法允许一个对象从另一个对象借用方法,而无需复制。
示例
// object definition
const student1 = {
name: "Jack",
grade: "5",
introduction: function () {
console.log(this.name + "studies in grade" + this.grade + ".");
},
};
// object definition
const student2 = {
name: "Jimmy ",
grade: " 6",
};
// the object student2 is borrowing introduction method from student1
let result= student1.introduction.bind(student2);
// invoking introduction() function
result();
// Output:
// Jimmy studies in grade 6.
bind() 语法
bind()
方法的语法是
func.bind(thisArg, arg1, ... argN)
其中,func
是一个函数。
bind() 参数
bind()
可以接受两个参数
thisArg
- 为func
提供的作为this参数的值。arg1, ... argN
(可选) -func
中存在的参数值。
注意:如果未指定thisArg
,则执行作用域的this被视为thisArg
。
bind() 返回值
- 返回给定函数的副本,并指定
this
值和初始参数(如果提供)。
示例 1:使用 bind() 方法
// object definition
const student1 = {
name: "Jack",
grade: "5",
introduction: function () {
console.log(this.name + "studies in grade" + this.grade + ".");
},
};
// object definition
const student2 = {
name: "Jimmy ",
grade: " 6",
};
// the object student2 is borrowing introduction method from student1
let result= student1.introduction.bind(student2);
// invoking result() function
result(); // Jimmy studies in grade 6.
输出
Jimmy studies in grade 6.
在上面的示例中,我们定义了两个对象 student1 和 student2。
由于 student2 没有 `introduction()` 方法,我们使用 `bind()` 函数从 student1 借用它。
student1.introduction.bind(student2)
返回 `introduction()` 的副本并将其赋值给 result。
示例 2:使用带两个参数的 bind() 方法
// object definition
const student1 = {
name: "Jack",
introduction: function (score) {
console.log(this.name + "scored " + score + " in an exam.");
},
};
// object definition
const student2 = {
name: "Jimmy ",
};
// passing two parameters student2 and '95'
let result = student1.introduction.bind(student2, 95);
// invoking result() function
result(); // Jimmy scored 95 in an exam.
输出
Jimmy scored 95 in an exam.
在上面的示例中,我们在 `bind()` 中传递了两个参数 thisArg 和 arg1。
将 student2 对象作为 `this` 参数传递,并将 **95** 作为 score 参数的参数值。
另请阅读