简体   繁体   中英

What's the difference between str.fun() / str.fun / fun(str) in JavaScript?

I tried googling but couldn't find a precise answer, so allow me to try and ask here. If the question does not seem proper, please let me know and I'll delete it.

In JS you've got three different way of writing certain build in functionalities:

  • str.length
  • str.toString()
  • parseInt(str)

I wonder if there is a reason behind these different ways of writing. As a new user I don't grasp why it couldn't be streamlined as: length(str) / toString(str) / parseInt(str) or with dot formulation.

I however think if I do know the reason behind these differences, it would give me a better understanding of JavaScript.

Length is one of the attributes of string in JavaScript. Hence you use string.length to get the length of the string. toString is a function for string objects, hence we use stringobj.toString(). parsInt(str) is a global function which takes string as a parameter.

JavaScript is object-oriented, so there are functions or procedures which require first an object to use as this in their bodies. str.length is a property, both syntactically and semantically. It doesn't require any parameters and represents some quality of the object. obj.toString() is a method (a function attached to an object), which doesn't represent any characteristics of the object, but rather operates on its state, computes some new values, or changes the state of the object a lot. parseInt(str) is a "global" function, which represents an operation not attached to any type or object.

Under the hood, these three ways may be well implemented with just calling a function, passing this as the first parameter (like C# does, for example). The semantic difference is the important one.

So why not use just the third syntax, like for example PHP does? First, it doesn't bloat the global environment with lots of functions which only work for one specific case and type, allowing you to specify any new function you want without breaking the old functionality. Second, it ecourages you to use object-oriented concepts, because you can already see working objects and methods in the language, and can try to make something similar.

And why isn't parseInt a method? It can as well be str.toInt() without any issues, it's just the way JavaScript designers wanted it to be, although it seems also a bit logical to me to make it a static method Number.parseInt(str) , because the behaviour of the function is relevant more to the Number type than the String type.

Behaviour of these expressions is defined in ECMAScript grammar. You could read the specification to understand it thoroughly: ECMAScript2015 specification . However, as pointed out by Bergi, it's probably not the best resource for beginners because it doesn't explain anything, it just states how things are. Moreover I think it might be too difficult for you to be able to grasp concepts described in this specification because of the very formal language used.

Therefore I recommend to start with something way simpler, such as a very basic introduction to JavaScript: JavaScript Basics on MDN . MDN is a great resource.

But to answer your question just briefly:

  • str.length is accessing a property of the str object.
  • parseInt(str) is a function call
  • str.toString() is a call of a function which is a property of the str object. Such functions are usually named methods .

Functions and methods are in fact very similar but one of the differences (except for the obvious syntax difference) is that methods by default have context ( this ) set to refer to the object which they're part of. In this case inside of toString function this equals to str .

Note : Accessing a property (as in str.length ) could in effect call a getter function but it depends on how the object is defined, and is in fact transparent for the user.

JavaScript is based around objects. Objects have properties (eg a User object may have name and age properties). These are what define the user and are related to the user. Properties are accessed via dot-notation or brackets notation (to access Eliott's age, we'll use either eliott.age or eliott['age'] — these are equivalent).

These properties can be of any type — String, Number, Object, you name it — even functions. Now the proper syntax to call a function in JS is to put round brackets: eliott.sayHello() . This snippet actually fetches Eliott's sayHello property, and calls it right away.

You can see Eliott as a box of properties, some of which can be functions. They only exist within the box and have no meaning out of the box: what would age be? Whose age? Who's saying hello?

Now some functions are defined at the global level: parseInt or isNaN for instance. These functions actually belong to the global box, named window (because legacy). You can also call them like that: window.parseInt(a, 10) or window.isNaN(a) . Omitting window is allowed for brevity.

var eliott = {
  name: 'Eliott',
  age: 32,
  sayHello: function () { console.log('Hello, I’m Eliott'); }
};

eliott.name;       // access the `name` property
eliott.age;        // access the `age` property
eliott.sayHello;   // access the `sayHello` property

eliott.sayHello(); // access the `sayHello` property and calls the function

sayHello(eliott);  // Reference error: `window.sayHello` is undefined!

Note: Some types ( String , Number , Boolean , etc.) are not real objects but do have properties. That's how you can fetch the length of a string ( "hello".length ) and reword stuff ( "hello, Eliott".replace("Eliott", "Henry") ).

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