How best to inherit from native JavaScript object? (Especially String)

后端 未结 4 1986
北恋
北恋 2021-02-12 18:01

I\'m a long-time browser but a first time participator. If I\'m missing any etiquette details, please just let me know!

Also, I\'ve searched high and low, including this

4条回答
  •  庸人自扰
    2021-02-12 18:37

    This line is not valid:

    this = n;
    

    this is not a valid lvalue. Meaning, you cannot assign to the value referenced by this. Ever. It's just not valid javascript. Your example will work if you do:

    var myString = function (n){
        this.prop = n;
    
        this.a = function (){
            alert(this.prop);
        };
    }
    
    myString.prototype = new String; // or String.prototype;
    
    var x = new myString("foo");
    x.a();
    

    Regarding your workaround, you should realise that all you're doing is making a String object, augmenting a function property, and then calling it. There is no inheritance taking place.

    For example, if you execute x instanceof myString in my example above it evaluates to true, but in your example it isn't, because the function myString isn't a type, it's just a regular function.

提交回复
热议问题