San*_*osh 6 javascript prototype micr
我有一个原型模型,我需要在原型中包含以下扩展方法:
String.prototype.startsWith = function(str){
return (this.indexOf(str) === 0);
}
Run Code Online (Sandbox Code Playgroud)
示例:[JS]
sample = function() {
this.i;
}
sample.prototype = {
get_data: function() {
return this.i;
}
}
Run Code Online (Sandbox Code Playgroud)
在原型模型中,如何使用扩展方法或任何其他方式在JS原型模型中创建扩展方法.
Jon*_*øgh 13
在字符串上调用新方法:
String.prototype.startsWith = function(str){
return (this.indexOf(str) === 0);
}
Run Code Online (Sandbox Code Playgroud)
应该简单到:
alert("foobar".startsWith("foo")); //alerts true
Run Code Online (Sandbox Code Playgroud)
对于你的第二个例子,我假设你想要一个设置成员变量"i"的构造函数:
function sample(i) {
this.i = i;
}
sample.prototype.get_data = function() { return this.i; }
Run Code Online (Sandbox Code Playgroud)
您可以按如下方式使用:
var s = new sample(42);
alert(s.get_data()); //alerts 42
Run Code Online (Sandbox Code Playgroud)