使用JavaScript对象文字表示法的JavaScript构造函数 [英] JavaScript constructors using JavaScript object literal notation
问题描述
使用对象文字符号在JavaScript中构建构造函数的最佳方法是什么?
What is the best way to build constructors in JavaScript using object literal notation?
var myObject = {
funca : function() {
//...
},
funcb : function() {
//...
}
};
我希望能够打电话
var myVar = new myObject(...);
并将参数传递给myObject内的构造函数.
And pass the arguments to a constructor function inside myObject.
推荐答案
这不是不是"JSON表示法",这是JavaScript 对象文字表示法. JSON只是JS对象文字表示法的一个子集,但是除了看起来相似之外,它们没有任何共同点. JSON被用作数据交换格式,例如XML.
This is not "JSON notation", this is JavaScript object literal notation. JSON is only a subset of JS object literal notation, but apart from looking similar, they have nothing in common. JSON is used as data exchange format, like XML.
不可能做.
var myObject = {};
已经创建了一个对象.没有什么可以实例化的.
creates already an object. There is nothing what you can instantiate.
不过,您可以创建一个构造函数并将方法添加到其原型中:
You can however create a constructor function and add the methods to its prototype:
function MyObject(arg1, arg2) {
// this refers to the new instance
this.arg1 = arg1;
this.arg2 = arg2;
// you can also call methods
this.funca(arg1);
}
MyObject.prototype = {
funca : function() {
// can access `this.arg1`, `this.arg2`
},
funcb : function() {
// can access `this.arg1`, `this.arg2`
}
};
您用new MyObject()
实例化的每个对象都将继承原型的属性(实际上,实例只是获得对原型对象的引用).
Every object you instantiate with new MyObject()
will inherit the properties of the prototype (actually, the instances just get a reference to the prototype object).
有关JavaScript对象和继承的更多信息:
More about JavaScript objects and inheritance:
- Working with objects
- Details of the object model
- Inheritance revisited
Update2:
如果必须实例化许多相同种类的对象,请使用构造函数+原型.如果您只需要一个对象(如单例),则无需使用构造函数(大部分时间).您可以直接使用对象文字表示法创建该对象.
If you have to instantiate many objects of the same kind, then use a constructor function + prototype. If you only need one object (like a singleton) then there is no need to use a constructor function (most of the time). You can directly use object literal notation to create that object.
这篇关于使用JavaScript对象文字表示法的JavaScript构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!