function bind()
JavaScript函数
bind()方法用于创建新函数。调用函数时,它将自己的this关键字设置为具有给定参数序列的给定值。
语法
function.bind(thisArg [, arg1[, arg2[, ...]]]
参数
thisArg -将此值传递给目标函数。
arg1,arg2,。 ...,argn -表示该函数的参数。
返回值
它返回给定函数的副本,前提是此值和初始参数。
JavaScript函数bind()方法示例
示例1
让我们看一个简单的示例的bind()方法。
<script>
var website = {
name: "lidihuo",
getName: function() {
return this.name;
}
}
var unboundGetName = website.getName;
var boundGetName = unboundGetName.bind(website);
document.writeln(boundGetName());
</script>
输出:
lidihuo
示例2
让我们看一个bind()方法的示例。
<script>
// Here, this refers to global "window" object
this.name = "Oracle";
var website = {
name: "lidihuo",
getName: function() { return this.name; }
};
document.writeln(website.getName()); // lidihuo
//It invokes at global scope
var retrieveName = website.getName;
document.writeln(retrieveName()); //Oracle
var boundGetName = retrieveName.bind(website);
document.writeln(boundGetName()); // lidihuo
</script>
输出:
lidihuo Oracle lidihuo