javascript继承问题

时间:2010-10-29 10:03:35

标签: javascript ajax inheritance

我有两个对象,一个继承自另一个。 父对象发送ajax请求以发送一些联系电子邮件。

如果我使用孩子发送请求,所有数据都是空的......为什么? 发送ajax请求(也发送到右侧URL),但数据对象为空。

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();
}

这是继承对象:

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

1 个答案:

答案 0 :(得分:0)

您将对象的原型样式与per-instance-members-with-this-closure样式的对象混合在一起。这不行。

问题是:

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

conteact_B.prototype = new contact_A;

现在,self的值始终是this构建new contact_A时的值。那就是:self将始终是原型对象,而不是contact_B实例。

因此,只要使用self,它就会针对原型对象而不是实例运行;它不会看到constructor中分配的任何成员属性。

为避免混淆,请从原型或此封闭对象中选择一个。有关背景信息,请参阅this discussion