【问题标题】:Using jQuery on Object Oriented Javascript files在面向对象的 Javascript 文件上使用 jQuery
【发布时间】:2012-11-04 01:51:25
【问题描述】:

我正在使用面向对象为我的项目创建脚本文件,并且我还使用 jQuery 和 Datatables 等框架/小部件。

我在我的类上创建的公共属性无法从通过 jQuery 代码执行的函数的内部范围访问。

这是一个示例:

    function MyClass() {
        this.MyProperty = '';
    }

    MyClass.prototype.initialize = function() {
            $(document).ready(function(){
            alert(this.MyProperty); // MyProperty is undefined at this point
        }
    };

我该如何解决这个问题?这是拥有可以从类的每个成员访问的属性的正确方法吗?

【问题讨论】:

  • 你想通过这一切达到什么目的?

标签: javascript jquery oop


【解决方案1】:

存储this

 function MyClass() {
        this.MyProperty = '';
    }

    MyClass.prototype.initialize = function() {
            var that=this;
            $(document).ready(function(){
            // in event handler regardless of jquery this points 
            // on element which fire event. here this === document,
            alert(that.MyProperty); // MyProperty is defined at this point
        }
    };

【讨论】:

  • 谢谢。正是我需要的。
【解决方案2】:

这是因为this 不指向您的类,而是指向该函数中的document。当它指向您的类时,您需要存储它所指向的内容:

function MyClass() {
    this.MyProperty = '';
}

MyClass.prototype.initialize = function() {
    var myClassInstance=this;
    $(document).ready(function(){
        alert(myClassInstance.MyProperty); // Will contain the property
    });
}

【讨论】:

    【解决方案3】:

    $.proxy 可以帮助解决这个问题,

    function MyClass() {
        this.MyProperty = '';
    }
    
    MyClass.prototype.initialize = function() {
        $(document).ready($.proxy(function(){
            alert(this.MyProperty);
        },this));
    };
    

    【讨论】:

      【解决方案4】:

      这与其他的有点不同,但更容易使用。保留在 initialize() 函数本身之外分配“this”上下文的逻辑。您的独特案例可能会使该解决方案无效,但我认为无论如何我都会分享。

      function MyClass() {
         this.MyProperty = '';
         $(function(){
            this.initialize();
         }.call(this));
      }
      
      MyClass.prototype.initialize = function () {
         alert(this.MyProperty);
      }
      

      【讨论】:

        猜你喜欢
        • 2011-05-24
        • 2010-10-31
        • 2012-02-10
        • 1970-01-01
        • 2010-10-22
        • 2010-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多