function Article() { this.tag = ["js", "html"]; } var article = new Article(); var Blogpost = function () {}; Blogpost.prototype = article; var blog = new Blogpost(); var Page = function() { Article.call(this, arguments); }; var page = new Page(); blog.tag.push("aa"); page.tag.push("bb"); console.log(article);
Object {tag: Array[3]}
blog和article是同一个tag引用。是同一个实例,article。
如果将Blogpost.prototype = new Article();重新new 一个那么实例就不共享了。
new的适合,构造函数的新的实例,但是prototype是共享的。如下所示
function Tree (x) { this.value = x; } Tree.prototype = { constructor: Tree, children: [], addChild: function(x) { this.children.push(x); } } var tree1 = new Tree(1); tree1.addChild(1); var tree2 = new Tree(2); tree2.addChild(2); console.log (tree1.children);//[1,2]