将jQueryajax回调参数定义为现有对象类型

Defining a jQuery ajax callback parameter as an existing object type

本文关键字:对象 类型 定义 jQueryajax 回调 参数      更新时间:2023-09-26

我承认这个问题已经到了我对JavaScript&jQuery,可能有一种更合适的方式来陈述我的问题(这将有助于找到现有的解决方案),但如果你能忍受我,这就是我想要的。

我已经定义了一个现有的对象类。我正在使用getJSON进行jQueryajax调用,我希望我的回调参数(它是一个对象)被归类为我的自定义对象,这样我就可以从中访问该类的方法。

所以我有一些对象类

function Boo() {
  this.param1;
  this.param2;
  this.yah = function() {
     ...
  }
}

然后我有其他类似的东西

$.getJSON(url,function(new_instance) {
   //from my php source this passed object is already loaded with param1, param2...
   alert(new_instance.param1);    //no probs
   //but i want to be able to then call
   new_instance.yah();
});

换句话说,我希望new_instance被认为是Boo()的一个实例。我知道在ActionScript这样的东西中,你必须对传入的参数进行分类,正是因为这个原因,不知道我在JS中有多大的灵活性。

我可能想过用一个中间函数来接收传入的对象并创建/填充Boo()的新实例,但不确定是否有更聪明的方法。

非常感谢!!

不要在构造函数中定义方法,否则每次成本构建者都会一遍又一遍地定义它们被调用。将它们移到原型:

Boo.prototype = {
    yah: function() {
    },
    bah: function() {
    }
    ...
};

一个小助手功能:

function coerceTo( proto, values ) {
    var r = Object.create( proto );
    for( var key in values ) {
        r[key] = values[key];
    }
    return r;
}

根据浏览器的不同,Object.create可能不可用,因此:

if (!Object.create) {
    Object.create = function (o) {
        if (arguments.length > 1) {
            throw new Error('Object.create implementation only accepts the first parameter.');
        }
        function F() {}
        F.prototype = o;
        return new F();
    };
}

用法:

new_instance = coerceTo( Boo.prototype, new_instance );
new_instance instanceof Boo //true
new_instance.yah();

您可以做什么:

$.getJSON(url,function(newObjData) {
   var newObj = $.extend(new Boo(), newObjData);
   newObj.yah();
});

还要考虑将Boo方法移动到对象prototype,这样就不会为每个Boo实例重新创建方法:

var Boo = function() {
    this.param1;
    this.param2;
}
Boo.prototype.yah = function() {
    console.log(this.param1);
}