简体   繁体   English

JavaScript 构造函数使用 JavaScript object 文字表示法

[英]JavaScript constructors using JavaScript object literal notation

What is the best way to build constructors in JavaScript using object literal notation?使用 object 文字符号在 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.并将 arguments 传递给 myObject 内部的构造函数 function。

This is not "JSON notation", this is JavaScript object literal notation . 不是 “JSON表示法”,这是JavaScript 对象字面表示法 JSON is only a subset of JS object literal notation, but apart from looking similar, they have nothing in common. JSON只是JS对象文字表示法的一个子集,但除了看起来相似之外,它们没有任何共同之处。 JSON is used as data exchange format, like XML. 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: UPDATE2:

If you have to instantiate many objects of the same kind, then use a constructor function + prototype. 如果必须实例化许多相同类型的对象,则使用构造函数+ 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. 您可以直接使用对象文字表示法来创建该对象。

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'});

Sorry for being late to the party, but... I think saying that this is not possible is 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. 假设OP需要命名空间的好处,对象文字符号可以带给库,但也希望在该结构中使用一些“类”。 Could you not use something of this form to combine constructor patterns in to an object literal notation namespaced library structure? 你能否使用这种形式的东西将构造函数模式组合成对象文字符号命名空间的库结构?

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. 它消除了人们通常希望对库使用对象文字符号的全局拥挤问题。

var myObject = function(arg){
    return{
        constructor: function(arg){
            //...
            return this;
        },

        funca: function(){
            //...
        },

        funcb: function(){
            //...
        }
    }.constructor(arg);
};

//...

var myVar = new myObject("...");
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 );

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();

Well, calling new on the object literal is not possible, as others already answered.好吧,正如其他人已经回答的那样,不可能在 object 文字上调用new

But calling new on the object literal constructor is possible.但是在 object 文字constructor上调用new是可能的。

 var obj = { arg1: null, arg2: null }; var obj1 = new obj.constructor(); var obj2 = new obj.constructor(); obj1.arg1 = 1; obj2.arg1 = 2; console.log("obj2.arg1:", obj2.arg1); console.log("obj1.arg1:", obj1.arg1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM