我正在尝试创建自定义字符串方法。
我不确定如何获取字符串的值,该方法附加到该函数并传回给函数。
function testPrototyping(passedVar) {
passedVar += " reason why this is not working";
return passedVar;
}
String.prototype.testMethod = testPrototyping;
var myVar = "some";
var myVar2;
// 1. This works but is not what I want:
myVar2 = myVar.testMethod(myVar);
// 2. This is what I want but doesn't work:
myVar2 = myVar.testMethod();
// 3. Wondering if this should work also:
myVar2 = testMethod(myVar);
答案 0 :(得分:3)
您需要像{}一样使用this
:
function testPrototyping() {
var text = this;
text = text.trim();
text + " reason why this is not working";
return text;
}
String.prototype.testMethod = testPrototyping;
“的StackOverflow” .testMethod()
Prototype方法中的关键字this
指的是构造函数实例。您可以在此处详细了解"this"。
答案 1 :(得分:2)
如果您想引用当前字符串,可以使用this
关键字:
function testPrototyping() {
return this + " reason why this is not working";
}
但是,您无法为this
分配任何内容。所以this += "..."
无效。
答案 2 :(得分:0)
可以通过testPrototyping
内的this
访问对象包装器testPrototyping
。 String对象包装器的实际底层字符串可通过valueOf()
方法获得:
String.prototype.showStuff = function() {
console.log(this);
console.log(this.valueOf());
console.log(this + ' proves that conversion is done automatically');
console.log(typeof this, 'but it is not ok in every situation');
};
var myVar = "test";
myVar.showStuff();
/* results (Chrome 32):
String {0: "t", 1: "e", 2: "s", 3: "t", length: 4, formatUnicorn: function, truncate: function, splitOnLast: function, contains: function…}
test
test proves that conversion is done automatically
object but it is not ok in every situation
*/
答案 3 :(得分:0)
你不能完全按照自己的意愿去做,因为字符串在javascript中是不可变的。这意味着您无法在不创建新字符串的情况下更改字符串。
根据您真正需要实现的目标,您可以使用另一个对象来“隐藏”真正的字符串:
var MyString = function(s) {
this.s = s;
};
MyString.prototype.toString = function() {
return this.s;
};
MyString.prototype.testMethod = function() {
this.s += " reason why this is working";
};
var myVar = new MyString("some");
alert(myVar); // "some"
myVar.testMethod();
alert(myVar); // "some reason why this is working"