简体   繁体   English

Javascript中的toString()和toLocaleString()属性和/或方法?

[英]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 ? Object定义时,Javascript属性和/或方法中的toString()toLocaleString()是什么?

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. 在Javascript中,情况更有趣,因为变量可以保存一个函数。 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. 所以在你的例子中,toString和toLocaleString都是方法。

If you are interested, please refer to this great resource: 如果您有兴趣,请参考以下优秀资源:

Javascript: The Definitive Guide - 8.3. Javascript:权威指南 - 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. 对于所有JavaScript对象,“toString”和“toLocaleString”属性的值应该是一个函数,将调用该函数来检索对象的字符串表示形式。

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. 为了回答我认为你的问题标题所暗示的内容,JavaScript中“方法”的概念并不存在。 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. 也就是说,函数只是函数,并且“this”对象直到函数调用时才被绑定,因此没有对象“拥有”函数作为方法的概念,它可能恰好具有属性其价值观是方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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