js中的prototype

参考文献:阮一峰的博客

  http://www.ruanyifeng.com/blog/2011/06/designing_ideas_of_inheritance_mechanism_in_javascript.html

  http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_encapsulation.html

1、为什么会出现prototype

  Every JavaScript object has a prototype. The prototype is also an object.All JavaScript objects inherit their properties and methods from their prototype.所有的js对象都有一个prototype,这个prototype也是一个对象。

  在使用构造函数模式,实例对象时。对于不变的属性和方法,要放在prototype属性上,这样他们在内存中只生成一次。如果是都放在中,没生成一个实例就多生成一次,多占用内存。

  因此,在prototype中存放的是不变的属性以及方法。

2、构造函数创建对象的方式

        function Person(name, age) {
            this.name = name;
            this.age = age;
        }
        //prototype放各实例共享的变量、方法
        Person.prototype = {
            des: "人类",
            eat: function () {
                console.log('eat');
            }
        }
        var person1 = new Person("person1", 12);
        person1.eat();
        console.log(person1.des);
        console.log(person1.name);
        console.log(person1.age);    

   运行截图:

  

原文地址:https://www.cnblogs.com/zhaoyihao/p/6344391.html