使用文字和自定义构造函数创建Javascript对象 [英] Javascript object creation using literals vs custom constructor functions

查看:72
本文介绍了使用文字和自定义构造函数创建Javascript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以使用多种方法在javascript中创建对象,并且我一直在阅读对象字面量语法通常是首选. (正确吗?)

I understand that there are multiple ways to create an object in javascript and I have been reading that object literal syntax is generally preferred. (Correct?)

我一直无法弄清楚的是,是否有理由使用其他任何方式创建对象,例如自定义构造函数(var p = new Person("Adam"))?仅当我想要私有变量或向其原型添加方法或属性时才使用自定义构造函数吗?没有办法用文字来完成这些操作吗?

What I haven't been able to figure out is if there is ever a reason to use any of the other ways to create objects, such as a custom constructor function (var p = new Person("Adam"))? Is it true to use a custom constructor function only if I want private variables or to add methods or properties to its prototype? Is there no way to do these in a literal?

推荐答案

当您要创建类似于Java的对象实例时,可以使用自定义构造函数.

You can use the custom constructor function when you want to create instances of objects, similar to Java.

例如:

function MyObj(x){
   this.x = x;
}

MyObj.prototype.printX = function(){
   alert(this.x);
}

var obj1 = new MyObj("hello");
var obj2 = new MyObj("hello2");
obj1.printX();//prints hello
obj2.printX();//prints hello2

现在我有此对象的两个实例.如果我使用String文字,则需要将对象克隆到新的var中,以获得另一个实例.

Now I have two instances of this object. If I used String literals I would need to clone the object into a new var in order to get another instance.

这篇关于使用文字和自定义构造函数创建Javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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