使用 JavaScript 对象字面量表示法的 JavaScript 构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5179271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript constructors using JavaScript object literal notation
提问by mrwooster
What is the best way to build constructors in JavaScript using object literal notation?
使用对象文字表示法在 JavaScript 中构建构造函数的最佳方法是什么?
var myObject = {
funca : function() {
//...
},
funcb : function() {
//...
}
};
I want to be able to call
我希望能够打电话
var myVar = new myObject(...);
And pass the arguments to a constructor function inside myObject.
并将参数传递给 myObject 中的构造函数。
回答by Felix Kling
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 exchangeformat, like XML.
这不是“JSON 表示法”,这是 JavaScript对象文字表示法。JSON 只是 JS 对象文字符号的一个子集,但除了看起来相似之外,它们没有任何共同之处。JSON 用作数据交换格式,如 XML。
It is not possible what you want to do.
你想做什么是不可能的。
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`
}
};
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).
您实例化的每个对象都new MyObject()
将继承原型的属性(实际上,实例只是获得对原型对象的引用)。
More about JavaScript objects and inheritance:
有关 JavaScript 对象和继承的更多信息:
Update2:
更新2:
If you have to instantiate many objects of the same kind, then use a constructor function + prototype. If you only need oneobject (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.
如果您必须实例化许多相同类型的对象,则使用构造函数+原型。如果您只需要一个对象(如单例),则无需使用构造函数(大多数情况下)。您可以直接使用对象文字表示法来创建该对象。
回答by Simeon
Make the object a function, like this:
使对象成为一个函数,如下所示:
var myObject = function(arg1){
this.funca = function(){
//...
};
this.funcb = function(){
//...
};
this.constructor = function(obj){
alert('constructor! I can now use the arg: ' + obj.name);
};
this.constructor(arg1);
};
// Use the object, passing in an initializer:
var myVar = new myObject({ name: 'Doug'});
回答by Klors
Sorry for being late to the party, but... I think saying that this is not possibleis a little restrictive depending on how you interpret the OP's question and subsequent comments.
很抱歉迟到了,但是...我认为根据您对 OP 的问题和后续评论的解释,说这是不可能的有点限制性。
Assuming the OP wanted the namespacing benefits that object literal notation can bring to a library but also wanted to have some "classes" to use within that structure. Could you not use something of this form to combine constructor patterns in to an object literal notation namespaced library structure?
假设 OP 想要对象文字符号可以为库带来的命名空间优势,但也想要在该结构中使用一些“类”。难道你不能使用这种形式将构造函数模式组合到对象文字符号命名空间库结构中吗?
var myNamespace = {
aProperty: "A value",
aMethod: function () { return "A method result"; },
onePlusOneEquals: function () {
return new myNamespace.classes.NumberStuff(1, 1).added;
},
classes: {
ClassA: function () {
this.propertyOne = null;
this.methodOne = function (param) {
return "The method was passed " + param;
}
},
NumberStuff: function (argOne, argTwo) {
this.added = argOne + argTwo;
this.subtracted = argOne - argTwo;
}
}
};
myNamespace.classes.ClassA.prototype.methodTwo = function () { return "At least this one's not bloating our memory footprint with every ClassA created..."; };
...
var anObj = new myNamespace.classes.ClassA();
alert(anObj.methodOne("the parcel")); // "The method was passed the parcel"
alert(myNamespace.onePlusOneEquals()); //2
They're silly examples, but is there any reason not to do this, or why this isn't valid? It gets rid of the global crowding problem that people usually want to use object literal notation for with libraries.
他们是愚蠢的例子,但有什么理由不这样做,或者为什么这无效?它摆脱了人们通常希望对库使用对象字面量表示法的全局拥挤问题。
回答by user3295430
var myObject = function(arg){
return{
constructor: function(arg){
//...
return this;
},
funca: function(){
//...
},
funcb: function(){
//...
}
}.constructor(arg);
};
//...
var myVar = new myObject("...");
回答by rajesh_kw
var myObject = {
funca : function() {
//...
},
funcb : function() {
//...
}
};
you can not create a new object of above this way
您不能以这种方式创建上面的新对象
var myVar = new myObject(...);
but you can achieve the same with below construct,
但是您可以使用以下构造实现相同的目的,
var myVar = Object.create(myObject );
回答by Delirium tremens
The simplest way I know is:
我知道的最简单的方法是:
function test(arg1, arg2) {
var1 = arg1;
var2 = arg2;
return {
var3 : var1, // json can access var1
var4 : var2 // json can access var2
};
}
arg1 = 'test';
arg2 = function() {
window.alert('test')
};
var5 = new test(arg1, arg2);
var5.var4();