问题一:一个方法封装在一个对象中时,直接封装和通过prototype封装两种方法有什么区别?var Apple = {};
Apple.prototype.size = function size() { // do something};
Apple.size = function size() { // do something};var app1 = new Apple();var app2 = new Apple();关于prototype,我的印象是好像和原型的动态性、prototype的方法时公用的什么的有关系,一旦app1的size改动会影响到app2的size。但是在我目前接触的项目中,大概是这样的var City = function city(node) { this.node = document.querySelector(node); this.size = null;
……
…… this.location = {};
};
City.prototype.a = function a() {};
City.prototype.b = function b() {};
City.prototype.c = function c() {};
City.x = function x() { // do something}问题二:这里不涉及对实例的改动,但是为什么最后的x方法不用原型而要直接这样写(哈哈,这种写法叫什么?赋值?)呢?
1 回答

侃侃无极
TA贡献2051条经验 获得超10个赞
问题一:
直接封装会造成内存浪费,每次new都会开辟新的内存。而通过prototype则没有这个问题,因为都是引用。
问题二:
这种写法相当于静态方法,就是无需new即可进行调用。例如Math对象的方法都是这样。
添加回答
举报
0/150
提交
取消