0

I am writing this method encodedURIComponentValue() for Javascript string:

the idea is to allow me to call : "some string".encodedURIComponentValue()

The code is as:

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

but in some case it does not work:

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

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

Any idea ?

Dio Phung
  • 5,944
  • 5
  • 37
  • 55

2 Answers2

1

You may find the following answer helpful as it explains prototype, constructor function and the value of this.

In this case I would not advice doing it like you do. You don't own String and modifying it breaks encapsulation. The only "valid" situation would be if you need to implement an existing method to support older browsers (like Object.create). More info on that here.

You could do what you're doing with:

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

So other then liking the other syntax there really isn't any reason for it.

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160
0

OK, it is my stupid mistake - the str is the parameter which was never supplied. So I changed to this and it works:

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

Hope I will understand more about this keyword in Js

Dio Phung
  • 5,944
  • 5
  • 37
  • 55