开发者

javascript inheritnace problem

I have two objects, and one inherites from the other. the parent object sends an ajax request to send some contact email.

if i use the child to s开发者_JS百科end the request, all data is empty ... why is that? the ajax request is sent (to the right url as well) but the data object is empty.

var contact_A = function(){
    var self = this;
    this.url = '/xxx/xxx/xxx';

    this.constructor = function(){ 

        this.dialog = $('.contact_box');

        this.sender = this.dialog.find('input[name=sender]');
        this.name = this.dialog.find('input[name=name]');
        this.content = this.dialog.find('textarea[name=content]');

        ...
    }

    this.init = function(){
       ...
       this.dialog.find('.button_blue').bind('click', function(){
           var data = self.process_form();
          if(data != false) self.send(data);
        });
        ...
    }

    this.process_form = function(){

        this.validator =  new validator('contact_box', true);
        if(this.validator.validate(true)) {

            var data = {
                sender: this.sender.val(),
                name: this.name.val(),
                content: this.content.val()
            }

            return data;
        } else return false;
    }

    this.send = function(data){

        $.ajax({
            type: "POST",
            url: self.url,
            data: data,
            success: function(msg){
                //if not successful
                self.successful(msg);
            },
            async: true
        });

        this.close();
    }

    ...

    this.constructor();
    this.init();
}

and this is the inheriting object:

var conteact_B = function(){
    var self = this;
    this.constructor();
    this.init();    
}
conteact_B.prototype = new contact_A;
conteact_B.prototype.url = '/yyy/yyy/yyy';


You're mixing the prototype style of object with the per-instance-members-with-this-closure style of object. This doesn't work well.

The problem is:

var contact_A = function(){
    var self = this;
    ... do stuff with self ...
};

conteact_B.prototype = new contact_A;

Now the value of self will always be what this was when the new contact_A was constructed. That is: self will always be the prototype object, and never the contact_B instance.

So whenever self is used, it'll be running against the prototype object and not the instance; it won't see any of the member properties assigned in the constructor.

To avoid confusion, pick one out of prototypes or this-closure objects. See this discussion for some background.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜