Reputation: 7041
function test(){
String.prototype.to_selector=function(a){return "#"+a;}
return "asd".to_selector();
}
I want "asd".to_selector();
not working outside the function. How to do it? Or is it necessary?
Upvotes: 1
Views: 90
Reputation: 169411
function test(){
String.prototype.to_selector=function(a){return "#"+a;}
var o = "asd".to_selector();
delete String.prototype.to_selector;
return o;
}
Upvotes: 2
Reputation: 12793
It is not possible by modifying String
prototype, since this would modify all the instances of String that you create after this function is executed.
I don't see the need of having a method for a native object that only works inside a specific function scope. What's the use case? You can always add a static method to the String
object or a instance method to the String
prototype (not a good practice, mind you) and only use it inside test
.
You can also create a new object that you can use for that purpose, although you lose the elegance of calling to_selector
directly from a string declaration:
var string2 = function(str) {
this.str = str;
};
string2.prototype = {
to_selector: function() {
return '#' + this.str;
},
toString: function() {
return this.str;
}
};
function test(){
asd = new string2("asd");
return asd.to_selector();
}
But again, I can't see how this would be convenient at all.
Upvotes: 2
Reputation: 122936
No, that's not possible, and in your example it's not really useful I'd say. Why not just use:
function test(){
var to_selector = function(a){return "#"+a;};
return to_selector("asd");
}
If you assign a prototype method for a native Object (String
here), it's assigned for all subsequent calls to that Object.
You can assign a method directly to a genuine String
Object but again I don't really see any use cases for that:
var test = function(a){
var str = new String(a);
str.to_selector = function(){return "#"+this;}
return str.to_selector();
}
alert(test('asd')); //=> '#asd'
alert('bla'.to_selector()); //=> error
Upvotes: 2