咨询JavaScript中call()方法内的this指向,附相关代码示例
Hey there! Let's break down your question about call() and this in JavaScript, plus work through the code snippet you shared.
this in the call() Method First off, the call() method exists to let you invoke a function while explicitly setting what this points to inside that function. When you write functionName.call(context, arg1, arg2, ...), the this keyword inside functionName will reference the context object you pass as the first argument. Super straightforward—unless you mix it with other patterns like constructor functions, which we'll get to.
Let's Walk Through Your Code Line by Line
Let's start with the first part of your code:
function hello(val) { console.log(this, val); } console.log(hello('jumbo'))
- When you call
hello('jumbo')directly (withoutcall/apply/bindornew), in JavaScript's default non-strict mode,thisinside thehellofunction points to the global object—that'swindowin browsers, orglobalThisin Node.js. If you ran this in strict mode (add'use strict';at the top of your function),thiswould beundefinedinstead. - Also, notice that
hellodoesn't return any value, soconsole.log(hello('jumbo'))will first log thethisand'jumbo'from insidehello, then logundefined(since that's whathelloreturns).
Now the second part, which has a small issue:
let obj = { 'name':'Pranjal' }; var h = new hello.call(this, obj)
Wait a minute—this line will throw a syntax error! Here's why:
- The
newkeyword expects a constructor function (or a class) to create an instance from it. Buthello.call(this, obj)immediately invokes thehellofunction right then and there, and sincehelloreturns nothing, it gives backundefined. You can't usenewonundefined—it just doesn't work. - If your goal was to create a new instance of
hellowhile settingthistoobj, that's a bit tricky because when you usenew, it overrides anythiscontext set bycall,apply, orbind. Even if you didnew (hello.bind(obj))('test'), thethisinsidehellowould still point to the newly created instance, notobj. Constructors always prioritize the new instance forthis.
Quick Key Takeaways
- For regular
call()usage:func.call(context)makesthisinsidefuncpoint tocontext. - Direct function calls:
thisis the global object (non-strict) orundefined(strict). - You can't combine
newwithfunc.call()directly—call()runs the function immediately, so there's no constructor left to usenewon.
内容的提问来源于stack exchange,提问作者Pranjal Sharma

