简体   繁体   中英

Are toString() and toLocaleString() properties and/or methods in Javascript?

Are toString() and toLocaleString() in Javascript properties and/or methods, when defined in an Object ?

If not both, what does this mean:

var person1 : {
    toString = function(){
      return "Hello";
    },
    toLocaleString : {
       return "Halo";
    }
};

Objects can have either methods and properties. Properties are basically variables, methods are functions. In Javascript, the situation is a bit more interesting, because a variable can hold a function. But still, if you have functions as properties in your object, they are considered methods.

So in your example both toString and toLocaleString are methods.

If you are interested, please refer to this great resource:

Javascript: The Definitive Guide - 8.3. Methods

For all JavaScript objects the value of the "toString" and "toLocaleString" properties is expected to be a function which will be called to retrieve the string representation of the object.

There are a few problems with your example code, see my corrections below:

var person1 = { // Assign a new literal object to "person1"
  toString: function() { // With property "toString" as a function...
    return "Hello";
  },
  toLocaleString: function() { // ...and "toLocaleString" as a function.
    return "Halo";
  }
}; 

To answer what I think your question title alludes to, the concept of "methods" in JavaScript doesn't really exist. That is, functions are just functions, and the "this" object isn't bound until the time of a function call, so there is no concept of an object "owning" a function as a method, it can just happen to have properties whose values are methods.

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