Javascript 使用encodeURIComponent()的字符串原型自定义方法

Javascript 使用encodeURIComponent()的字符串原型自定义方法,javascript,prototype,encodeuricomponent,Javascript,Prototype,Encodeuricomponent,我正在为Javascript字符串编写此方法encodedURIComponentValue(): 其思想是允许我调用:“some string”。encodedURIComponentValue() 守则如下: if (typeof String.prototype.encodedURIComponentValue != 'function') { String.prototype.encodedURIComponentValue = function (str) {

我正在为Javascript字符串编写此方法
encodedURIComponentValue()

其思想是允许我调用:
“some string”。encodedURIComponentValue()

守则如下:

if (typeof String.prototype.encodedURIComponentValue != 'function') {
    String.prototype.encodedURIComponentValue = function (str) {
        if (str && str.length > 0)
            return encodeURIComponent(str);
        else
            return "";
    };
}
但在某些情况下,它不起作用:

var encodedVal = $("body").find("option:selected").first().text().encodedURIComponentValue() // text() = "Option1" 

console.log(encodedVal); // I only see "" (empty)

知道吗?

好吧,这是我愚蠢的错误,
str
是从未提供的参数。 所以我改成了这个,它起作用了:

if (typeof String.prototype.encodedURIComponentValue != 'function') {
    String.prototype.encodedURIComponentValue = function () {
        if (this && this.length > 0)
            return encodeURIComponent(this);
        else
            return "";
    };
}
希望我能更多地了解Js中的
这个
关键字

您可能会发现它在解释原型、构造函数和
这个
的价值时很有帮助

在这种情况下,我不建议像你那样做。您不拥有字符串,修改它会破坏封装。唯一“有效”的情况是,如果您需要实现一个现有的方法来支持较旧的浏览器(如Object.create)。更多信息

你可以做你正在做的事情:

encodeURIComponent(
  $("body").find("option:selected").first().text()
);

因此,other then喜欢其他语法,这真的没有任何理由。

这里不需要if分支:encodeURIComponent(“”==“”)