JS - 将变形basetype变为子类型

时间:2014-07-08 15:11:34

标签: javascript prototype prototypal-inheritance

JS中有一种简单的方法可以将基类型更改为已定义的子类型吗?这是否有意义(有没有人有任何关于何时可以以合理有用的方式使用它的例子)。

人为的例子(可能存在语法错误):

var animal = function(id){
  this.init(id);
}
cat.prototype.init = function(id){this.id = id;}
cat.prototype.eat = function(){something...};

var cat = function(name, fur){
  this.fur=fur;
  this.init(id);
}
cat.prototype = new animal();

var myanimal = new animal(getNextId()); //maybe it's a petstore or something that needs animals in their DB.
//myanimal needs to become a cat now.

1 个答案:

答案 0 :(得分:1)

  

JS有一种简单的方法可以将基类型更改为已定义的子类型吗?

没有。但是有一种复杂的方法,changes the prototype然后重新应用子类型构造函数。

  

这有什么意义吗?

不,绝对不是。你做这样的事情只是为了重用对象(object pool作为性能优化),但altering the [[prototype]] defeats that purpose

只需创建一个新实例:

myanimal = new cat(myanimal.id); // use id of old animal, and overwrite variable