美文网首页
浅谈prototype和构造函数

浅谈prototype和构造函数

作者: JRSS | 来源:发表于2017-08-01 14:11 被阅读0次

    构造函数

        function Animal(name) {
            this.name = name;
            this.eat = function() {
                console.log(this.name + "吃老鼠");
            }
        }
        var a = new Animal('猫');
        var b = new Animal('狗');
        console.log(a.eat == b.eat);    //false
    


    构造函数生成的对象实例中的方法eat,在各自的实例上面都创建为新的函数,两个函数各自引用自己的内存,造成资源的浪费

    prototype

    function Person(name) {
            this.name = name;
        }
        Person.prototype.eat = function() {
            console.log(this.name + '吃早餐');
        }
        var aa = new Person('张三');
        var bb = new Person('李四');
        console.log(aa.eat == bb.eat); //true
    
    张三
    李四

    prototype生成的对象实例中的方法eat,共同引用Person原型上面的eat方法,节省资源

    总结

    推荐使用prototype创建对象,更节省内存,更有效率。

    相关文章

      网友评论

          本文标题:浅谈prototype和构造函数

          本文链接:https://www.haomeiwen.com/subject/ljejlxtx.html