美文网首页
js给某个对象添加方法是添加到原型上还是直接挂到这个对象上好?

js给某个对象添加方法是添加到原型上还是直接挂到这个对象上好?

作者: 小李不小 | 来源:发表于2020-12-23 21:59 被阅读0次

    new Object()创建对象是没有prototype的,你向utils.prototype添加方法是会报错的,
    除非你把方法添加在Object.prototype上


    image.png

    prototype是函数的一个属性(每个函数都有一个prototype属性);
    你得创建一个构造函数,他才有prototype;


    image.png

    原型方法可以这样添加:

    UtilsClass.prototype.methodA = function(){console.log(1111)}
    

    然后new一个 utils对象出来,你能在utils.proto上找到methodA

    var utils = new UtilsClass();
    

    使用原型增加方法,有利于内存的减少

    function User(name){
        this.name=name; 
    }
       console.dir(User)
    
    //使用原型增加方法,有利于内存的减少
    // User.prototype.show=function(){ console.log(this.name);console.log(this)}
    User.prototype={
       constructor:User,
        show(){
            console.log(this.name)
            console.log(this.__proto__.constructor== User)
        }
    }
    
    var lisi=new User('李四')
    console.log(lisi)
    lisi.show();
    

    相关文章

      网友评论

          本文标题:js给某个对象添加方法是添加到原型上还是直接挂到这个对象上好?

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