开发者

Is it possible to apply prototype of an Object inside a function closure only?

function test(){
    String.prototype.to_selector=function(a){return "#"+a;}
    return "asd".to_selector();
}

I want "asd".to_selector(); not work开发者_如何学Pythoning outside the function. How to do it? Or is it necessary?


function test(){
    String.prototype.to_selector=function(a){return "#"+a;}
    var o = "asd".to_selector();
    delete String.prototype.to_selector;
    return o;
}


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜