使用对象文字表示法在JavaScript中构建构造函数的最佳方法是什么?
var myObject = {
funca : function() {
//...
},
funcb : function() {
//...
}
};
Run Code Online (Sandbox Code Playgroud)
我希望能够打电话
var myVar = new myObject(...);
Run Code Online (Sandbox Code Playgroud)
并将参数传递给myObject中的构造函数.
Fel*_*ing 46
这不是 "JSON表示法",这是JavaScript 对象字面表示法.JSON只是JS对象文字表示法的一个子集,但除了看起来相似之外,它们没有任何共同之处.JSON用作数据交换格式,如XML.
你不想做什么.
var myObject = {};
Run Code Online (Sandbox Code Playgroud)
创建一个对象.没有什么可以实例化的.
但是,您可以创建构造函数并将方法添加到其原型中:
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`
}
};
Run Code Online (Sandbox Code Playgroud)
您实例化的每个对象都new MyObject()将继承原型的属性(实际上,实例只是获取对原型对象的引用).
有关JavaScript对象和继承的更多信息:
UPDATE2:
如果必须实例化许多相同类型的对象,则使用构造函数+ prototype.如果您只需要一个对象(如单例),则无需使用构造函数(大多数情况下).您可以直接使用对象文字表示法来创建该对象.
使对象成为一个函数,如下所示:
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'});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31871 次 |
| 最近记录: |