Learning javascript OOP III
时间:2010-07-17 来源:handy-wang
1) 进一步讨论定义在构造器内部的public method 与 定义在prototype上的public method.
Person = (function() {
return function() {
// Private instance methods
var name = "handy";
var age = "18";
// Public instance methods
this.getInfo = function() {
return name + " had been " + age + " years old.";
};
}
})();
上面的这种方式就是定义在构造器内部的public method. 这种方式对于JAVA, Objective-C 等纯面向对象语言的developers来说很习惯, 但是它有一个不好的地方就是当new多个Person实例时, 会在内存中创建多个getInfo这个function的实例,尤其当getInfo这个function做的是一些复杂逻辑、代码量大的时候,相应占的 内存就是一个function的N倍。于是引出了另一种定义public method的方式。如下:
Person = (function() {
return function() {
// Private instance methods
var name = "handy";
var age = 18;
}
})();
Person.prototype = {
getInfo : function() {
// It's wrong. Can't access name and age variable, because of scope.
return name + " had been " + age + " years old.";
}
};
这种方式的好处就是当在new多个Person实例时, getInfo只会在内存中创建一份。不好的地方就是不能访问私有成员。只能通过调用public method来访问私有成员,再对私有成员进行操作。如下:
Person = (function() {
return function() {
// Private instance methods
var name = "handy";
var age = 18;
this.getName() {
return name;
}
this.getAge() {
return age;
}
}
})();
Person.prototype = {
getInfo : function() {
return this.getName() + " had been " + this.getAge() + " years old.";
}
};
所以,个人体会是:如果一个public method做的事少,代码量小,可以放到构造器内部定义,这样代码要整洁一些;如果public method做的事多且代码量大,那么最好还是定义到prototype里。
最后,还有一种方式来代替在构造器里定义操作数据的method.当然这种method就不是public的了,它是private static 里。如下:
Person = (function() {
// Assume these functions do complex logics and huge codes.
var operations = {
getInfo : function(name, age) {
return name + " had been " + age + " years old.";
}
};
return function() {
// Private instance methods
var name = null;
var age = 0;
this.getName() {
return name;
}
this.getAge() {
return age;
}
this.getDetail() {
return getInfo(name, age);
}
}
})();
采用以上这种方式后,每new一个Person实例后,operations是一个静态的对外不可见的变量,所以里面的方法在内存中都只有一份。
最后总结,个人推荐最后一种方式。
2) this的小论。
i) 在一个不属于任何类的functioin中访问this,此时this表示window。如下validityCheck方法:
Person = (function() {
// Assume these functions do complex logics and huge codes.
var operations = {
getInfo : function(name, age) {
return name + " had been " + age + " years old.";
}
};
return function() {
// Private instance methods
var name = null;
var age = 0;
this.getName() {
return name;
}
this.getAge() {
return age;
}
this.getDetail() {
return getInfo(name, age);
}
function validityCheck() {
// Do some check jobs.
alert(this.toString());
}
}
})();
这时alert出来的内空就是window.
ii) 在构造器里访问this时,this表示的是类的实例。如下所有的get方法:
Person = (function() {
// Assume these functions do complex logics and huge codes.
var operations = {
getInfo : function(name, age) {
return name + " had been " + age + " years old.";
}
};
return function() {
// Private instance methods
var name = null;
var age = 0;
this.getName() {
return name;
}
this.getAge() {
return age;
}
this.getDetail() {
return getInfo(name, age);
}
}
})();
所以这些get方法可以通过实例访问到也就是public method.










