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 complex and somewhat overkill, compared to a single-line code :)
Edit: Thanks for your answers !
__proto__ Deprecated: This feature is no longer recommended.
In JavaScript, an object can inherit properties of another object. The object from where the properties are inherited is called the prototype. In short, objects can inherit properties from other objects — the prototypes.
__proto__ is a way to inherit properties from an object in JavaScript. __proto__ a property of Object. prototype is an accessor property that exposes the [[Prototype]] of the object through which it is accessed. POSTly is a web-based API tool that allows for fast testing of your APIs (REST, GraphQL).
The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With