【问题标题】:Javascript prototype extension methodJavascript原型扩展方法
【发布时间】:2009-09-11 09:01:21
【问题描述】:

我有一个原型模型,我需要在原型中包含以下扩展方法:

String.prototype.startsWith = function(str){
    return (this.indexOf(str) === 0);
}

示例: [JS]

sample = function() {
    this.i;
}

sample.prototype = {
    get_data: function() {
        return this.i;
    }
}

在原型模型中,如何使用扩展方法或其他方式在JS原型模型中创建扩展方法。

【问题讨论】:

    标签: javascript prototype micr


    【解决方案1】:

    在字符串上调用新方法:

    String.prototype.startsWith = function(str){
        return (this.indexOf(str) === 0);
    }
    

    应该很简单:

    alert("foobar".startsWith("foo")); //alerts true
    

    对于您的第二个示例,我假设您需要一个设置成员变量“i”的构造函数:

    function sample(i) { 
        this.i = i;     
    }
    
    sample.prototype.get_data = function() { return this.i; }
    

    您可以按如下方式使用它:

    var s = new sample(42);
    alert(s.get_data()); //alerts 42
    

    【讨论】:

    • 我需要在示例原型中添加 thastartswith 方法.. hw 来做 tat...
    • 对不起,我不明白你想要什么
    【解决方案2】:

    构造函数应该以大写字母开头。

    function Sample(i) { 
        this.i = i;     
    }
    
    var s = new Sample(42);
    

    【讨论】:

      【解决方案3】:

      不确定这是否正确,但请尝试此代码。它在 IE 中对我有用。

      在 JavaScript 文件中添加:

      String.prototype.includes = function (str) {
          var returnValue = false;
      
          if(this.indexOf(str) != -1){
      
              returnValue = true;
          }
      
          return returnValue;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-01-15
        • 1970-01-01
        • 2016-07-29
        • 2021-01-27
        • 1970-01-01
        • 1970-01-01
        • 2018-07-12
        • 2013-01-28
        • 2013-12-02
        相关资源
        最近更新 更多