更简单的原型语法

77 阅读1分钟

为什么要把重复的方法写在原型对象里面

这样更好的节约内存,是代码更加的优化简介,不用写更多的代码,不会生成一个实例对象就加载一次,就好比有一百个呢·岂不是要加载一百次,所以写在原型对象里面就便于用到的时候调用其余时候也不占内存

function Person(name, age) {
    this.name = name
    this.age = age }
    // Person.prototype.type = '中国人' 
    // Person.prototype.eat = function () { 
        // console.log(this.name, '吃饭'); 
    // } 
    // Person.prototype.say = function () {
    // console.log(this.name,'说话'); 
    // } 
    Person.prototype = { 
        constructor: Person, //简写形式,手动添加constructor指向构造函数 
        type:'中国人', 
        eat:function(){ 
            console.log(this.name, '吃饭'); 
        }, 
        say:function(){ 
            console.log(this.name,'说话');
            } 
        } 
        let p1 = new Person('jack',20) 
        p1.eat() 
        p1.say() 
        
        console.dir(Person.prototype)\