In-depth interview questions on understanding the Call method
- Call implementation source code
Function.prototype.call = function call(context, ... params) {
// The context is passed as null so that it equals the window object
context == null ? context = window : null
Context must be a value of object type: only objects can set properties
2 -> Object(2) -> Number{}
!/^(object|function)$/.test(typeof context) ? context = Object(context) : null
const self = this
let result = null
// Add attribute names to ensure uniqueness and prevent contamination of members of the original object
const key = Symbol('KEY')
context[key] = self // context[key] = call functionresult = context[key](... params)// Take the corresponding key, this refers to the corresponding object
delete context[key] // Remove your new attributes when you are done using them
return result
}
Copy the code
var name = 'yaochengjian'
function A(x, y) {
var res = x + y
console.log(res, this.name)
}
function B(x, y) {
var res = x - y
console.log(res, this.name)
}
B.call(A, 40.30)
B.call.call.call(A, 20.10)
Function.prototype.call(A, 60.50)
Function.prototype.call.call.call(A, 80.70)
Copy the code