20190115 q:

How to implement a Call, Apply, and Bind?

Similarities:

  • Both are used to borrow methods and specify that this refers to the scene
  • The first argument is always the object to which this refers
  • Can be passed by subsequent parameters

Difference:

  • Parameters are passed in different ways
  • Call,apply is called immediately,bind is called dynamically

Basic use:

Array. The prototype. Slice. Call (obj, 0) Array. The prototype. Slice. Apply (obj, [0]) Array. The prototype. Slice. Bind (obj) (0)Copy the code

As you can see from the above example, call and apply are used almost identically, while bind actually returns a function

Easy BIND implementation

Function.prototype.bind = function(context){
    const _this = this
    return function() {
        _this.apply(context, Array.prototype.slice.call(arguments))
    }
}
Copy the code

Bind only implements scoped binding of methods. The parameters are already fixed. If you want dynamic parameters, you’ll have to rewrite them

Function.prototype.bind = function(context){
    const _this = this
    const argus = Array.prototype.slice.apply(arguments,[1])
    return function() {
        _this.apply(context, argus.concat(Array.prototype.slice.call(arguments)))
    }
}
Copy the code

The issue of

What are some of the most common methods of web security attacks? And how to prevent it

JS daily question

JS Question of the day can be regarded as a voice answer community to complete the question of the day in the form of voice within 60 seconds with fragmented time every day, and the group owner will push the reference answer of the day at 0 o ‘clock the next day

  • Note is not limited to completing the task of the day, but more to check and fill in the gaps, learning from other students in the group excellent answer ideas

Scan the QR code below to join the answer