代码之家  ›  专栏  ›  技术社区  ›  Psytronic

在开发OOJ时,我应该引用原型函数还是变量版本?

  •  1
  • Psytronic  · 技术社区  · 14 年前

    正如标题(排序)所解释的,当我在JS中进行原型设计时,我需要引用对象的另一个函数,我应该访问它的原型版本还是局部变量版本?其中一项是否涉及(主要)间接费用问题?

    //starting off
    Foo = function(){ }
    
    Foo.prototype.ShowMessage = function(msg){
      alert(msg);
    }
    
    //method 1
    Foo.prototype.Validate = function(msg){
      //some validation stuff...
      if(!Valid){
        this.ShowMessage("Please check your inputs, there seems to be a problem with them.");
      }
    }
    
    //method 2
    Foo.prototype.Validate = function(msg){
      //some validation stuff...
      if(!Valid){
        Foo.prototype.ShowMessage("Please check your inputs, there seems to be a problem with them.");
      }
    }
    

    我更喜欢方法1,纯粹是因为它比foo.prototype更容易输入,但是哪一种方法的性能更重要?还是我只是妈妈?

    2 回复  |  直到 14 年前
        1
  •  3
  •   Pointy    14 年前

    你一定要用

    this.showMessage("msg");
    

    第二个版本根本无法正常工作。为什么?因为调用 showMessage 将导致其“this”变量指向原型对象,而不是实例。这几乎肯定不是你想要的。

        2
  •  0
  •   fantactuka    14 年前

    如果您想要一个实例方法,您应该使用这个.*引用。否则,如果要使用类方法,可以使用以下方法:

    //starting off
    Foo = function() {
    };
    
    Foo.prototype.ShowMessage = function(msg) {
        alert("Instance message: " + msg);
    };
    
    Foo.ShowMessage = function(msg) {
        alert("Class message: " + msg);
    };
    
    Foo.prototype.Validate = function(msg) {
        //some validation stuff...
        if (!Valid) {
            this.ShowMessage("Please check your inputs, there seems to be a problem with them.");
            Foo.ShowMessage("Please check your inputs, there seems to be a problem with them.");
        }
    };