关于JavaScript中call()函数的若干技术疑问咨询
Hey there! Let's unpack each of your questions clearly since these are common gotchas when starting out with JS.
1. Why pass null as the first argument to call()?
The first parameter of call() is meant to set the value of this inside the function being called. When you pass null here, what happens depends on whether you're in strict mode or not:
- In non-strict mode (the default in most cases),
thiswill default to the global object (that'swindowin browsers,globalin Node.js). - In strict mode,
thiswill actually benull.
Most of the time, developers pass null here when the function they're calling doesn't rely on the this context at all. They're just using call() to pass arguments to the function in a structured way (or sometimes to "borrow" a method from another object without needing its context). For example, if you have a function like:
function logNumbers(a, b) { console.log(a, b); }
Calling logNumbers.call(null, 1, 2) works exactly the same as logNumbers(1, 2) because the function doesn't use this anywhere.
2. What's the purpose of the + before y.call(null, page, i, pages)?
That's the unary plus operator, and its job is to convert the result of the expression that follows it into a number.
For example:
- If
y.call(...)returns a string like"42",+y.call(...)will turn it into the number42. - If it returns a boolean (
true/false),+convertstrueto1andfalseto0. - If it returns an object, JavaScript will try to call its
valueOf()ortoString()method to get a primitive value to convert to a number (if that fails, you'll getNaN).
It's a quick way to coerce a value to a number type without writing something longer like Number(y.call(...)).
3. Can you do assignment operations inside argument parentheses (like value = ... in isNaN)?
Absolutely! JavaScript allows assignment expressions inside function arguments because every assignment in JS returns the value that was assigned.
For example:
let value; if (isNaN(value = parseInt("abc"))) { console.log("That's not a valid number!"); }
Here, value = parseInt("abc") first assigns NaN to value, then that NaN is passed to isNaN(), which returns true.
That said, while it's syntactically valid, it can make your code harder to read for other developers (or even future you). If the assignment isn't super straightforward, it's usually better to split it into two lines:
let value = parseInt("abc"); if (isNaN(value)) { console.log("That's not a valid number!"); }
内容的提问来源于stack exchange,提问作者Huyen

