Javascript jquery、简单继承和';这';

Javascript jquery、简单继承和';这';,javascript,jquery,ajax,inheritance,Javascript,Jquery,Ajax,Inheritance,因此,我尝试使用javascript和“简单继承”(根据)。为了“简化”事物,我的想法是创建对象并将它们附加到元素上,这样我就可以对它们进行操作 var Pane = Class.extend({ init: function( el ) { this.el = el; this.$el = $(el); return this; }, do_something: function() { this.$el.html('d

因此,我尝试使用javascript和“简单继承”(根据)。为了“简化”事物,我的想法是创建对象并将它们附加到元素上,这样我就可以对它们进行操作

var Pane = Class.extend({
    init: function( el ) {
        this.el = el; this.$el = $(el);
        return this;
    },

    do_something: function() {
        this.$el.html('doing something!');
        $.getJSON( '/somewhere.js', function(data){
            // write something to $el
        });
    }
});
我会有一些html,比如

<div id="my_div"></div>
<script>
    var p = new Pane( $('#my_div') )
    p.do_something()
</script>

var p=新窗格($('my#u div'))
p、 做某事

不幸的是,在ajax调用中,“this”变成了jquery对象,而不是我的Pane对象,因此我无法更新$el/my_div(这也使得我的想法有些毫无意义)。你知道我如何在getJSON调用中访问对象吗?

在getJSON调用之前,你能不能把它的值存储在do\u something中的一个变量中:

var currentpane=this

只需使用闭包(将此复制到外部的其他变量)

另一种方法是使用jQuery
$.proxy
(它会更改函数上下文)。像这样:

     ...
     do_something: function() {
         this.$el.html('doing something!');            
         $.getJSON( '/somewhere.js', $.proxy( function(data){  //Here we proxy
             this.$el.html("..."); //use 'this' normally
         }, this));  //Using 'this' as context
     }

如果您想继续继承,可以创建一个基类,该基类能够创建绑定到其实例的回调,如下所示:

var Bindable = Class.extend({
    bind: function( fn ) {
        var that = this;
        return function(){ return fn.apply( that, arguments ); };
    }
}
现在您可以扩展这个类并使用它的bind方法来创建回调

// extend Bindable
var Pane = Bindable.extend({
    init: function( el ) {
        this.el = el; this.$el = $(el);
        // don't return this, it's incorrect;
        //return this;
    },

    handleData: function( data ) {
        // grab an imaginary key from the data for demo purposes
        var stuff = data.key;
        this.$el.html( stuff );
    },

    do_something: function() {
        this.$el.html('doing something!');
        $.getJSON( '/somewhere.js', this.bind( this.handleData ) );
    }
});

你必须使用继承吗?也许您必须存储对var somewhereyep中调用的每个对象的引用-这正是解决方案!(我一点击提交就意识到了,但不允许回答我自己的问题…)谢谢!
// extend Bindable
var Pane = Bindable.extend({
    init: function( el ) {
        this.el = el; this.$el = $(el);
        // don't return this, it's incorrect;
        //return this;
    },

    handleData: function( data ) {
        // grab an imaginary key from the data for demo purposes
        var stuff = data.key;
        this.$el.html( stuff );
    },

    do_something: function() {
        this.$el.html('doing something!');
        $.getJSON( '/somewhere.js', this.bind( this.handleData ) );
    }
});