最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS __proto__ inheritance replacement - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 6

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.

发布评论

评论列表(0)

  1. 暂无评论