简体   繁体   中英

JavaScript: Difference between toString and toString()

I'm struggling to understand this JavaScript behaviour (javascript n00b alert!!!). Source of the question is a typo in my code which led to the undesired situation. What I wanted to know is the length of a certain number. For example, if its 100, then answer should be 3, if 5893 then answer should be 4 and so on. To achieve this what I did simply is convert number to a string and then invoke .length on the string.

private getNumberLength(num: number) {
    return num.toString().length;
}

In the above return statement, I had typo such that it looked like

return num.toString.length;

The result was no compilation error and getNumberLength always returned 1 . I fail to understand this (why 1 ?). Can somebody please help me understand this?

Below you can quickly test if you wish

 var num = 666; console.log('Length on toString(): ' + num.toString().length); console.log('Length on toString: ' + num.toString.length);

Looks like this is Javascript behavior of automatically boxing primitive values to its Object counterpart to call its method.

The function looks correct, but to answer your question (I don't understand the downvotes).

toString is a reference to the function. The reason why toString.length works is because as quoted from Mozilla.

Function.length = The length property indicates the number of parameters expected by the function.

So if you redeclare your function as

private getNumberLength(num: number, num2: number) {
    return num.toString().length;
}

getNumberLength.length will return 2. toString.length will return 1 as it only expects one parameter.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length

toString() is invoking the function toString (and getting its return value). This is performing the actual conversion to String.

All the best with Javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM