如何用对象文字表示法创建方法? [英] how to create a method in object literal notation?

查看:75
本文介绍了如何用对象文字表示法创建方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 Codeacademy.com 上开始了13天的网络编程,并且发现它是一个学习的好地方。但我有时还会误解事情。我总是在 w3school.com 上查看它们,但这次我找不到我需要的信息。因此,据我所知,首先有两种类型的创建对象:对象文字符号和第二种:对象构造函数。我已经了解到还有方法和函数,但我无法理解如何用对象文字表示法创建方法?在对象构造函数中,我只写:`

I have started web-programming for only 13 days on Codeacademy.com and find it a good place to learn. But I still sometimes misunderstand things. I always check them on w3school.com ,but this time I couldn't find the information that I needed. So as I learned there are 2 types of creating objects first: object literal notation and second: Object constructor. I have learned that there are also methods and functions, but I couldn't understand how to create a method in object literal notation? In object constructor I just write : `

var bob = new Object();
bob.age = 30;
bob.setAge = function (newAge)
{
bob.age = newAge;
};

在编写对象文字表示法时,能告诉我如何做同样的事。

Can you please tell me how to do the same when writing object literal notation.

var bob = {
age: 30
};


推荐答案

从语法上讲,变化非常简单:

Syntactically, the change is very simple :

var bob = {
  age: 30,
  setAge: function (newAge) {
    bob.age = newAge;
  }
};

但正如您所看到的,存在一个问题:在您的代码中它使用外部 bob 变量,所以如果你改变 bob 变量的值,这将不起作用。

But as you can see, there's a problem : as in your code it uses the external bob variable so this wouldn't work if you change the value of the bob variable.

您可以使用

var bob = {
  age: 30,
  setAge: function (newAge) {
    this.age = newAge;
  }
};

请注意,此时您应该检查您所需要的是否实际上一个类,如果你有几个可以带来一些性能改进实例。

Note that at this point you should check whether what you need isn't, in fact, a class, which would bring some performance improvements if you have several instances.

更新: ECMAScript 6现在允许以相同的方式定义方法,无论它们是否在对象文字中:

Update: ECMAScript 6 now allows methods to be defined the same way regardless of whether they are in an object literal:

var bob = {
  age: 30,
  setAge (newAge) {
    this.age = newAge;
  }
};

这篇关于如何用对象文字表示法创建方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆