我可以在对象中创建方法吗?

发布于 2024-10-26 15:28:18 字数 475 浏览 1 评论 0原文

我之前看到过这段代码,但不知道什么意思:

var person1 = {
    toLocaleString : function(){
      return "Nikolaos";
     },
    toString : function(){
      return "Nicholas";
    }
}

var person2 = {
   toLocaleString : function(){
      return "bum";
   },
   toString : function(){
       return "Greg";
   } 

}

var people = [person1, person2];
alert(people.toString());
alert(people.toLocaleString());

该函数是用toLocaleString和toString的方法创建一个对象吗??还是...??

I saw this code before, but I don't know what the meaning:

var person1 = {
    toLocaleString : function(){
      return "Nikolaos";
     },
    toString : function(){
      return "Nicholas";
    }
}

var person2 = {
   toLocaleString : function(){
      return "bum";
   },
   toString : function(){
       return "Greg";
   } 

}

var people = [person1, person2];
alert(people.toString());
alert(people.toLocaleString());

does the function create an object with the method of toLocaleString and toString??or...??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

归途 2024-11-02 15:28:18

该代码做了三件事:

  1. 使用对象字面量语法创建对象实例
  2. 使用匿名函数表达式创建函数并将它们绑定到对象的属性。 (函数是 JavaScript 中的第一类对象,因此您可以保留对它们的引用、传递引用等。)
  3. 具体来说,它重写了所有 JavaScript 对象从 Object 原型继承的两个标准函数。

让我们把它分解一下。

1) 对象字面量表示法:

var obj = {propName: propValue};

本例中的 {} 表示一个对象字面量。在对象字面量中,您可以编写 propName: propValuepropValue 分配给对象上名为 propName 的属性。这与:

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

您可以执行用逗号分隔的多个属性。例如:

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

创建一个具有三个属性的对象,两个属性具有字符串值,一个具有数字值。

请注意,右侧的处理方式与赋值一样,因此可以是出现在赋值语句右侧的任何内容:

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

如果您愿意,可以将属性名称放在引号中:

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

...这是可以方便地指定具有保留标记(如“if”或“return”)或以前保留的标记(如“class”)名称的属性,如果它们不在引号中,则会出现语法错误。

2)现在让我们看一下函数表达式:

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

这是一个函数表达式。它创建一个新函数并将对其的引用分配给变量f。您可以通过调用f()来调用它。

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

1 + 2)因此将其与对象文字表示法放在一起:(

var obj = {
    foo: function(name) {
        alert("Hi " + name);
    }
};
obj.foo("Fred"); // alerts "Hi Fred"

我不喜欢匿名函数, 我更喜欢我的函数有名称,但那是另一个话题了。)

3)最后:正如 maerics 指出的,该代码中使用的特定函数是 toStringtoLocaleString,两者都是JavaScript对象的标准函数。这意味着这些将覆盖标准版本,因此每当调用标准函数时都会返回给定值。

That code is doing three things:

  1. Using object literal syntax to create object instances
  2. Using anonymous function expressions to create functions and bind them to properties on the objects. (Functions are first-class objects in JavaScript, so you can keep references to them, pass the references around, etc.)
  3. Specifically, it's overriding two standard functions that all JavaScript objects inherit from the Object prototype.

Let's break it down a bit.

1) Object literal notation:

var obj = {propName: propValue};

The { and } in this case denote an object literal. Within an object literal, you can write propName: propValue to assign propValue to the property with the name propName on the object. This is the same as:

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

You can do multiple properties separated with commas. So for instance:

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

That creates an object with three properties, two with string values and one with a number value.

Note that the right-hand side are processed just like an assignment, and so can be anything that can appear on the right-hand side of an assignment statement:

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

The property names can be put in quotes if you like:

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

...which is handy for specifying properties that have the names of reserved tokens (like "if", or "return") or formerly-reserved tokens (like "class") where it would be a syntax error if they weren't in quotes.

2) Now let's look at function expressions:

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

That's a function expression. It creates a new function and assigns a reference to it to the variable f. You can call it by calling f().

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

1 + 2) So putting it together with object literal notation:

var obj = {
    foo: function(name) {
        alert("Hi " + name);
    }
};
obj.foo("Fred"); // alerts "Hi Fred"

(I don't like anonymous functions, I prefer my functions to have names, but that's another topic.)

3) And finally: As maerics pointed out, the specific functions that are being used in that code are toString and toLocaleString, both of which are standard functions of JavaScript objects. That means that those will override the standard version and so return the given values whenever the standard function would have been called.

吹泡泡o 2024-11-02 15:28:18

toString()toLocaleString() 方法由 规范语言。因此,数组(例如存储在“people”变量中的数组)似乎通过分别返回每个元素的字符串或“区域设置字符串”值来实现这些方法(至少在我们正在测试的网络浏览器中)。

也就是说,Array 类 toStringtoLocaleString 方法必须通过以下方式实现:

Array.prototype.toString = function() {
  var a = [];
  for (var i=0; i<this.length; i++) {
    a[i] = this[i].toString(); // Note "toString".
  }
  return a.join(",");
}

Array.prototype.toLocaleString = function() {
  var a = [];
  for (var i=0; i<this.length; i++) {
    a[i] = this[i].toLocaleString(); // Note "toLocaleString".
  }
  return a.join(",");
}

The toString() and toLocaleString() methods are implemented for all JavaScript objects by the specification of the language. So arrays (such as the one stored in the "people" variable) seem to implement those methods by returning each of their elements' string or "locale string" value, respectively (at least, in the web browsers we are testing).

That is, the Array class toString and toLocaleString methods must be implemented with something like:

Array.prototype.toString = function() {
  var a = [];
  for (var i=0; i<this.length; i++) {
    a[i] = this[i].toString(); // Note "toString".
  }
  return a.join(",");
}

Array.prototype.toLocaleString = function() {
  var a = [];
  for (var i=0; i<this.length; i++) {
    a[i] = this[i].toLocaleString(); // Note "toLocaleString".
  }
  return a.join(",");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文