javascript中functionName()和functionName.call()之间的区别

jon*_*bbs 2 javascript

希望标题是自我解释的,与仅编写functionName()相比,在Javascript中使用.call()方法的优点是什么??

Dav*_*rno 8

functionName.call()将对象实例作为其第一个参数.然后它functionName在该对象实例的上下文中运行(即"this"是指定的实例)


Ate*_*ral 5

如果你没有传递任何东西call(),它将是相同的; 该函数将以与调用相同的范围运行call():

function test() {
    alert(this);
}

test(); // alerts the window object
test.call(); // alerts the window object
Run Code Online (Sandbox Code Playgroud)

但是如果你传入一个对象call(),那么该对象将被用作范围:

test.call("hi"); // alerts "hi"
Run Code Online (Sandbox Code Playgroud)