面向对象的Javascript传递变量

时间:2017-10-06 15:13:41

标签: javascript

我试图通过整理一些凌乱的JavaScript来学习面向对象的javascript,并希望使其更加面向对象,但是当我将变量传递给它们时,这些方法似乎开始失败。

例如这就是我认为应该如何运作的方式:

function object() {
    this.helloWorld = function() {
      alert("hello world");
    }; 
    this.alertString = function(string) {
      alert(string);
    }
    this.init = function() {
      string = "Alert String";
      this.helloWorld();
      this.alertString(string);
    }
} 
var objectInstance = new object();
objectInstance.init();

所以这一切都运行正常,但是当与下面的ajax调用类似时,我的函数在this.redirectDetect(result)中失败;

this.search = function() {
    if (this.runsearch == 1) {
        this.disableAction();
        term = $("#search").val();
        this.buildSearchLayout();
        $('.sidebar-main').css('opacity', '0');
        $.ajax({url: "/catalogsearch/result/index/", type: "get", data: { ajax: "1", q: term}, dataType: "json",success: function(result){
            this.redirectDetect(result);
            this.renderAjax(result, term);
            this.noResults();
            this.initJavascript();
        }});
    }
};
this.redirectDetect = function(result) {
    if(result['html']['products_list'].split('<li class="item product product-item">').length - 1 == 1) {
        redirect = result['html']['products_list'].match(/href="(.*?)" class="product/)[1];
        window.location.href = redirect;
        return;
    }
};

0 个答案:

没有答案