You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询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.

Understanding 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 (without call/apply/bind or new), in JavaScript's default non-strict mode, this inside the hello function points to the global object—that's window in browsers, or globalThis in Node.js. If you ran this in strict mode (add 'use strict'; at the top of your function), this would be undefined instead.
  • Also, notice that hello doesn't return any value, so console.log(hello('jumbo')) will first log the this and 'jumbo' from inside hello, then log undefined (since that's what hello returns).

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 new keyword expects a constructor function (or a class) to create an instance from it. But hello.call(this, obj) immediately invokes the hello function right then and there, and since hello returns nothing, it gives back undefined. You can't use new on undefined—it just doesn't work.
  • If your goal was to create a new instance of hello while setting this to obj, that's a bit tricky because when you use new, it overrides any this context set by call, apply, or bind. Even if you did new (hello.bind(obj))('test'), the this inside hello would still point to the newly created instance, not obj. Constructors always prioritize the new instance for this.

Quick Key Takeaways

  • For regular call() usage: func.call(context) makes this inside func point to context.
  • Direct function calls: this is the global object (non-strict) or undefined (strict).
  • You can't combine new with func.call() directly—call() runs the function immediately, so there's no constructor left to use new on.

内容的提问来源于stack exchange,提问作者Pranjal Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:58:51