admin管理员组文章数量:1355051
I m using prototype inheritance as described in
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 / and it still looks a bit plex and somewhat overkill, pared to a single-line code :)
Edit: Thanks for your answers !
I m using prototype inheritance as described in https://developer.mozilla/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/blog/simple-javascript-inheritance/ and it still looks a bit plex and somewhat overkill, pared to a single-line code :)
Edit: Thanks for your answers !
Share Improve this question edited Mar 2, 2011 at 9:02 azerty asked Mar 1, 2011 at 16:38 azertyazerty 813 bronze badges3 Answers
Reset to default 6The 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.
本文标签:
版权声明:本文标题:javascript - JS __proto__ inheritance replacement - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743960011a2568849.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论