2016-11-25 71 views
2

将函数原型复制到另一个函数(如下所示)有什么危害。原型继承:将函数原型复制到另一个

function Person(){} 
Person.prototype = {}; 
function Author(){} 
Author.prototype = Person.prototype; 
+0

在其他问题中,原型上的'constructor'属性将被错误地设置。你想'Author.prototype = Object.create(Person.prototype);'。 – 2016-11-25 05:01:48

+0

@torazaburo感谢您提出这个问题。但是Author.prototype = Object.create(Person.prototype);将不会设置原型的正确构造函数。无论如何,您将不得不手动将其重新设置为原始功能。 –

回答

1

JS中的对象分配创建一个引用。

var o = {}; 
var c = o; 

现在两个物体oc指的是相同的对象。试图将一个对象的原型分配给另一个时,同样的规则适用。

Author.prototype = Person.prototype; 

现在既AuthorPerson的原型是指一个单独的对象。如果你将一些数据放在Author的原型属性中,那么Person也会有相同的数据。对于不同的对象来说,这是最不可能的

一个这样做的正确方法是

Author.prototype = Object.create(Person.prototype); 

在这里,您创建Author.prototype一个全新的对象 - 但Person对象继承。

0

因为您通过引用传递原型,这意味着两者都受到所有更改的影响。考虑:

function Person(){} 
Person.prototype = {}; 
function Author(){} 
Author.prototype = Person.prototype; 

Author.prototype.books = []; 

var bob = new Person(); 
console.log(bob.books); // this will be an empty array, not undefined as one would expect. 
0

附着方法为原型的理想方法是通过创建其通过实例创建的对象。

function Person(){ 
    this.test = "1"; 
} 
function Author(){} 
Author.prototype = new Person(); 

这样你创建一个新的人的实例和返回的对象被馈送到作者。

如果您只是复制它,该怎么办?

如果您只是简单地复制相同的实例在原型之间共享,则在一个原型中进行更改将全部体现出来。

function b(){ 
    this.test = 'a'; 
    this.test1 = function(){ 
     console.log('test1'); 
    } 
    this.test2 = function(){ 
     console.log('test2'); 
    } 
} 
function a(){ 

} 
function c(){ 

} 
a.prototype = new b(); 
var a1 = new a(); 
c.prototype = a.prototype; 
a.test = 'asdf'; 
console.log(c.test); 

数据对实例的唯一性将会丢失。