从现有对象动态创建新的 javascript 类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2342490/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:51:39  来源:igfitidea点击:

Dynamically creating a new javascript class from an existing object

javascriptdynamicclass

提问by jd.

Say I have the following code:

假设我有以下代码:

var album = new MyObject('album');

Assume that when the object is constructed, a bunch of properties relative to only albums are loaded via AJAX. Would it be possible to create an Albumclass so that at a later point, I may just do this:

假设在构造对象时,通过 AJAX 加载了一组仅与专辑相关的属性。是否可以创建一个Album类,以便稍后我可以这样做:

var anotherAlbum = new Album();

The Albumconstructor would automatically set the properties that are unique to album objects, based on what was loaded when creating MyObject('album')

Album构造函数将自动设置特有的专辑对象的属性,立足于打造什么时候加载MyObject('album')

采纳答案by jhurshman

JavaScript "classes", just like any other object, can be dynamically created. So, yes, this can be done.

JavaScript“类”,就像任何其他对象一样,可以动态创建。所以,是的,这是可以做到的。

You would do something like this in the code handling the AJAX response (assuming that the AJAX response was providing the name of the new "class", and it's in a variable called newClassName):

您将在处理 AJAX 响应的代码中执行类似的操作(假设 AJAX 响应提供新“类”的名称,并且它位于名为 newClassName 的变量中):

window[newClassName] = function() {
  // New class name constructor code
}

window[newClassName].prototype = {

  someProperty: "someValue",

  someMethod: function(a, b) {
  },

  someOtherMethod: function(x) {
  }
}

回答by Adrian Schmidt

JavaScript is prototypal, not classical, so if you think in terms of classes, you're doing it wrong.

JavaScript 是原型的,而不是经典的,所以如果你从类的角度考虑,你就错了。

You don't have to use the newoperator at all. You can create a new object using the object literal:

您根本不必使用new运算符。您可以使用对象字面量创建一个新对象:

var myObject = {attr1: 'val1', attr2: 'val2'};

Then you can create a new instance of that object:

然后您可以创建该对象的新实例:

var mySecondObject = Object.create(myObject);

Now you can change the attributes of mySecondObject, and if it has methods you can overload them just as easily:

现在您可以更改 的属性mySecondObject,如果它有方法,您可以同样轻松地重载它们:

mySecondObject.attr1 = "Hello";

mySecondObject.attr2 = function() {
                           return "World!";
                       };

And then mySecondObjectwill of course have all the properties that you gave myObjectat creation.

然后mySecondObject当然会拥有您myObject在创建时提供的所有属性。

Be aware that this is a simple version, and that this leaves all attributes 'public'. If you need some privacy, it can be achieved by adding some functions to the mix. It's a bit more complicated though, so let me know if you're interested...

请注意,这是一个简单版本,并且所有属性都为“公开”。如果您需要一些隐私,可以通过添加一些功能来实现。虽然有点复杂,所以如果你有兴趣,请告诉我......

回答by noah

This is actually the only for of inheritance that JavaScript has. JavaScript has prototypal inheritance(which can be used to recreate classical inheritance). That means that inheritance is from another object, not a class definition.

这实际上是 JavaScript 的唯一继承。JavaScript 具有原型继承(可用于重新创建经典继承)。这意味着继承来自另一个对象,而不是类定义。

To create an object that has all the properties of another object is simple:

创建一个具有另一个对象所有属性的对象很简单:

function Album() {
   // do whatever initialization you need to here, all the properties of album 
   // are available on 'this'
   // e.g.,
   doSomething(this.albumName);
}
Album.prototype = album;

var anotherAlbum = new Album();

回答by caltuntas

You can use Douglas Crockford's Functional Inheritance Pattern. Code from Javascript Good Parts book

您可以使用 Douglas Crockford 的功能继承模式。来自 Javascript Good Parts 书中的代码

var mammal = function (spec) {
    var that = {};

    that.get_name = function (  ) {
        return spec.name;
    };

    that.says = function (  ) {
        return spec.saying || '';
    };

    return that;
};

var myMammal = mammal({name: 'Herb'});


var cat = function (spec) {
    spec.saying = spec.saying || 'meow';
    var that = mammal(spec);
    that.purr = function (n) {
        var i, s = '';
        for (i = 0; i < n; i += 1) {
            if (s) {
                s += '-';
            }
            s += 'r';
        }
        return s;
    };
    that.get_name = function (  ) {
        return that.says(  ) + ' ' + spec.name +
                ' ' + that.says(  );
    return that;
};

var myCat = cat({name: 'Henrietta'});

It uses functions to decorate existing javascript objects with new functions and properties. Like this you can add new functions and properties on the fly to your existing object

它使用函数来装饰具有新函数和属性的现有 javascript 对象。像这样,您可以动态地向现有对象添加新的函数和属性

回答by Ehsun Shojaeenia

You can do this

你可以这样做

var NewClass=function(){
    this.id=null;
    this.name=null;
    this.show=function(){
        alert(this.id+" "+this.name;
    }
}
NewClass.prototype.clear=function(){
    this.id=null;
    this.name=null;
};

...

var ins1=new NewClass();
var ins2=new NewClass();