【问题标题】:Inheritance in Javascript using prototype使用原型继承Javascript
【发布时间】:2011-04-18 15:24:43
【问题描述】:

我正在尝试使用我的父函数来获得价值。这可能是个愚蠢的问题,但我无法找到有关如何做到这一点的直截了当的教程。

我知道在使用原型时可以

function handler (selector) {
    return selector;
}
 Object.prototype.alertLine = function () {
        alert(this);}

handler('hello').alertLine();

但仍会收到警报。但我想知道是否有办法在父函数中指定对象、字符串、数字,例如

function handler(selector) {
if (typeof(selector) == 'string'){
return String(selector);
}

if (typeof(selector) == 'number') {
 return Number(selector);
}

if (typeof (selector) == 'object') {
 return Object(selector);
}
}

handler.prototype.alertLine = function () {
 alert(this);
}

handler('hello').alertLine();

我不介意Handler 是否是一个对象,这仅在我使用此方法传递值时才重要。

提前谢谢你。

【问题讨论】:

    标签: javascript oop inheritance prototype


    【解决方案1】:

    如果您想做类似的事情,您需要实例化处理程序的对象,而不是将其作为方法使用。你想要一个function constructor

    function Handler(selector){
    
     if (typeof(selector) == 'string'){
      this.selector = String(selector);
     }
    
     if (typeof(selector) == 'number') {
      this.selector = Number(selector);
     }
    
     if (typeof (selector) == 'object') {
      this.selector = Object(selector);
     }
    
    }
    
    Handler.prototype.alertLine = function(){
      alert(this.selector);
    }
    
    var h = new Handler("hello");
    h.alertLine();
    

    【讨论】:

      【解决方案2】:

      “这个想法是让人们每次都在一行代码中重新初始化一个新对象,所以我想要的不是 var a = new Handler('hello'); a.alertLine(); 而不是这个改为这个 var a = new Handler; 然后每次引用一个新参数 a('hello').alertLine()"

      我不太确定你为什么要这样做,但这样的事情可能会对你有所帮助:

      var Handler = function() {
          var fun = function() {}
          fun.prototype.set = function(t) {this.t = t; return this;}
          fun.prototype.alertLine = function(){ alert(this.t); }
          return new fun;  
      }
      
      var a = Handler(); 
      a.set('foo').alertLine(); 
      

      http://jsfiddle.net/herostwist/yPSpT/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-28
        • 2018-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-17
        相关资源
        最近更新 更多