I m using prototype inheritance as described in https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/Proto
function MyString(data){this.data = data ;}
MyString.prototype = { data : null,
toString: function(){ return this.data ;}
} ;
MyString.prototype.__proto__ = String.prototype ;
Now I can use String functions and MyString functions on MyString instances.
But since __proto__
is deprecated, non standard and should be avoided, what would be the best way to inherists objects ?
I found http://ejohn.org/blog/simple-javascript-inheritance/ and it still looks a bit c开发者_运维知识库omplex and somewhat overkill, compared to a single-line code :)
Edit: Thanks for your answers !
The ECMAScript 5 specification includes a new function Object.create()
that allows you to create a generic object with a specific prototype. To get the behaviour you want you'd do:
MyString.prototype = Object.create(String.prototype)
MyString.prototype.toString = ....
Object.create
can be used to create an arbitrarily long prototype chain, simply by chain return values along. Unfortunately it doesn't give us the ability to mutate an existing object's prototype chain (so it doesn't solve the Array "inheritance" problem)
Probably:
MyString.prototype = new String;
After doing this you can augment the prototype with your methods :)
When you say:
MyString.prototype.__proto__ = String.prototype ;
You're saying that the runtime should look at String.prototype
for properties of MyString.prototype
that are not declared in MyString.prototype
directly. But that's a roundabout way of saying what you were trying to say, which is that instances of MyString
should have the same properties and methods as a String
.
You say that like this:
MyString.prototype = new String();
__proto__
is a property of object instances. It's the runtime link back to the object that serves as that instance's prototype. On the other hand, prototype
is a property of constructor functions. It is the template for all objects created with that constructor.
精彩评论