JS: apply() Second, the context of the function

[Title] Description
will perform the function fn context object obj to
input examples:

speak(function () {
    
    
return this.greeting + ', ' + this.name + '!!!';
}, {greeting: 'Hello', name: 'Rebecca'}
)

Output example:

Hello, Rebecca!!!

Idea
According to the requirements of the topic, it is [ function context ], change the [ execution context ] of the fn function to [ obj object ]! ! !
Still use apply() method

apply(obj,args): hijack the method of another object and inherit the properties of another object.

obj: This object will replace [ this object ] in the Function class

args: This is [ array ], it will be passed to Function as an argument (args–>arguments)

Code

/*
-注意输入的例子中,fn函数里有了this,所有要根据题意,找个什么东东替换掉它,就是要劫持this对象的方法和属性
-因为是说函数的上下文,所以用obj替换掉this
*/
function speak(fn,obj){
    
    
 return fn.apply(obj,obj);
}

The first function on apply (obj, argument). obj, why write obj instead of this in the above example, because although there is this in the fn method, but I don’t know who this points to, and because the execution context of the fn function is changed to the obj object, I use obj. Then the this object in fn is obj.

Guess you like

Origin blog.csdn.net/sinat_35803474/article/details/68950863