借用构造函数继承非原型

        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]}
  1. tagArray[3]
    1. 0"js"
    2. 1"html"
    3. 2"aa"
    4. length3
    5. __proto__Array[0]
  2. __proto__Article
    1. constructorfunction Article() {
    2. __proto__Object

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]

 

原文地址:https://www.cnblogs.com/danghuijian/p/4583573.html