Js bind
var xw = {
name: "Zhang".gender: "Male".age: 24.say: function (school, grade) {
console.log(this.name + "," + this.gender + "Age" + this.age + "In the" + school + "On"+ grade); }}var xh = {
name: "Bill".gender: "Female".age: 18
}
xw.say.bind(xh,'tsinghua', primary school) ()/ / or
xw.say.bind(xh)('tsinghua'The primary school)Copy the code
Bind () returns a function body without a (), whereas call() and apply() execute the function directly. Here’s what I understand about the bind() implementation:
Function.prototype.bind2 = function (. context) {
let that = this
let value = context.slice(1) // Get the arguments passed in by bind(this, argument 1, argument 2)()
return function () {
let data = [].slice.call(arguments) // Convert class array arguments to a real array and get the arguments passed in by bind(this)(argument 1, argument 2)
that.apply(context[0], [...data, ...value]) Merge the parameters passed twice and call the apply() method}}Copy the code
This simply implements a bind2() method that is called in the same way as the bind() method