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

2020-12-23  本文已影响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();
上一篇下一篇

猜你喜欢

热点阅读