0

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

这个想法是让我打电话:"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)

任何想法 ?

4

2 回答 2

1

您可能会发现以下答案很有帮助,因为它解释了原型、构造函数和this.

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

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

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

所以除了喜欢其他语法之外,真的没有任何理由。

于 2014-06-25T08:03:17.030 回答
0

好的,这是我的愚蠢错误 -str是从未提供过的参数。所以我改变了这个并且它有效:

if (typeof String.prototype.encodedURIComponentValue != 'function') {
    String.prototype.encodedURIComponentValue = function () {
        if (this && this.length > 0)
            return encodeURIComponent(this);
        else
            return "";
    };
}

希望我能更多地了解thisJs 中的关键字

于 2014-06-25T06:59:20.297 回答