我有一个原型模型,我需要在原型中包含以下扩展方法:
String.prototype.startsWith = function(str){
return (this.indexOf(str) === 0);
}
实施例: [JS]
sample = function() {
this.i;
}
sample.prototype = {
get_data: function() {
return this.i;
}
}
在原型模型中,我如何使用扩展方法或任何其他方式在JS原型模型中创建扩展方法。
答案 0 :(得分:13)
在字符串上调用新方法:
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
答案 1 :(得分:1)
构造函数应该以大写字母开头。
function Sample(i) {
this.i = i;
}
var s = new Sample(42);
答案 2 :(得分:0)
不确定这是多么正确,但请尝试使用此代码。它在我的IE中工作。
添加JavaScript文件:
String.prototype.includes = function (str) {
var returnValue = false;
if(this.indexOf(str) != -1){
returnValue = true;
}
return returnValue;
}