我知道可以使用多种方法在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对象
发布评论