javascript - Can I create a method in an object? -


I saw this code before, but I do not know what it means:

  Var person1 = {toLocaleString: function () {return "Nikolaos"; }, ToString: function () {return "Nicholas"; }} Var person2 = {toLocaleString: function () {return "balm"; }, ToString: function () {return "Greg"; }} Var people = [person1, person2]; Warning (people.toString ()); Warning (people.toLocaleString ());   

Does one object with toLocaleString and toString method ?? Or ... ??

This code is doing three things:

  1. To create an object instance
  2. Use the Anonymous Function Expression to create an object instance to bind the properties of the properties on the object literal syntax objects. (Functions are first-class objects in javascript, so you can keep their references, send references around).
  3. Specifically, it is overriding the two standard tasks that all JavaScript Objects Object prototype

    Let's break it down a bit.

    1) Object Article Notation:

      var obj = {Proponent: ProVault};   

    In this case { and } indicates an object literally within any object, you < Code> propName: propValue to assign to propValue object name propName . This is the same:

      var obj = {}; // get an empty object obj.propName = propValue; // Add a property to it   

    You can do multiple properties separated by commas. For example:

      var obj = {author: "Douglas Adams", title: "The Hitchhiker's Guide to the Galaxy", Answer: 42};   

    It creates an object with three objects, two with string values ​​and one with a number value.

    Keep in mind that there may be an assignment on the right, and anything that can appear on the right side of an assignment statement:

      var x = "bar" ; Var obj = {three: 1 + 2, fub: "foo" + x};   

    If you wish, you can put the property name in quotes:

      var x = "bar"; Var obj = {"three": 1 + 2, "fiber": "foo" + x};   

    ... which is the name of a reserved token (such as "if", or "return") or pre-reserved token (like "class"), it is easy to specify This would be a syntax error if they were not in quotes.

    2) Now see the function expressions:

      var f = function () {/ * your code here}   

    This function is expression; it creates a new function and specifies a reference on the variable f for it. You can call it by calling f () .

      var f = function (name) {alert ("Hi" + name); }; F ("Fred"); // Alert "Hi Fred"   

    1 + 2) Then placing the object together with the literal signaling:

      var obj = {foo: function (Name)} {Warning ("Hi" + name); }}; Obj.foo ("Fred"); // Alert "Hi Fred"   

    (I do not like anonymous functions, but this is another topic.)

    3) And finally: as Marik did The specific functions used in that code are: toString and toLocaleString , both of which are standard functions of Javascript objects, that means they standard version < Em> override and whenever the standard function is called, return the given value.

Comments