【问题标题】:Calling javascript method from from inside object从对象内部调用 javascript 方法
【发布时间】:2010-05-12 01:56:50
【问题描述】:

我正在为 JavaScript 中的方法而苦苦挣扎。

  obj = function(){
    this.getMail = function getMail (){
    }
//Here I would like to run the get mail once but this.getMail() or getMail() wont work
    }


var mail = new obj();
mail.getMail();

我如何以一种可以在对象内部和外部运行的方式创建方法

谢谢

【问题讨论】:

    标签: javascript methods naming


    【解决方案1】:

    当您定义函数时,只需使用一次名称,如下所示:

    obj = function(){
      this.getMail = function(){
        alert("bob");
      }
    }
    

    现在你可以在那里使用this.getMail()you can see a working example here

    【讨论】:

    • 感谢您的链接,非常有用的工具。
    【解决方案2】:

    给你:

    var obj = function() {
    
        function getMail() {
            alert('hai!');
        }
    
        this.getMail = getMail;
        //Here I would like to run the get mail once but this.getMail() or getMail() wont work
    
        getMail();
    }
    
    var mail = new obj();
    mail.getMail();
    

    【讨论】:

      【解决方案3】:

      建议为您的对象建立一个健壮的定义。为它构建一个原型,然后如果您需要两个或更多,您可以制作它们的实例。我将在下面展示如何构建原型、添加相互调用的方法以及如何实例化对象。

      obj = function () {} //定义空对象

      obj.prototype.getMail = function () {  
      //this is a function on new instances of that object
         //whatever code you like
         return mail;
      }
      
      obj.prototype.otherMethod = function () { 
      //this is another function that can access obj.getMail via 'this'
          this.getMail();
      }
      
      var test = new obj; //make a new instance
      test.getMail();     //call the first method
      test.otherMethod(); //call the second method (that has access to the first)
      

      【讨论】:

      • 谢谢,不熟悉原型。我去看看
      猜你喜欢
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 2015-02-12
      相关资源
      最近更新 更多