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

mrw*_*ter 16 javascript json

使用对象文字表示法在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.如果您只需要一个对象(如单例),则无需使用构造函数(大多数情况下).您可以直接使用对象文字表示法来创建该对象.


Sim*_*eon 7

使对象成为一个函数,如下所示:

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)

  • JSON规范旨在与JavaScript对象互换.您是否知道JSON是**JavaScript Object Notation**的首字母缩写?Wiki的第一段总结得很好:http://en.wikipedia.org/wiki/JSON (2认同)
  • 我没有说你的回答是错的.但重要的是使用正确的术语并让人们意识到JSON不是JavaScript对象文字语法.使用通用(和正确)术语是沟通的关键.其他任何事都会造成混乱和误解...... (2认同)