如何用Javascript写一个Class?
记得前面某次面试被问到此问题,一直以来因为对JS的不重视+一知半解,所以当时就懵了~
最近Google了下,找到以下几种写Class的方式:
1 JS因为不是OO语言,所以没有Class的概念,都是通过ProtoType的方式实现的。
var namedClass = Class.create({
initialize: function(name) {
this.name = name;
}
getName: function() {
return this.name;
}
});
var instance = new namedClass('Foobar');
2 也可以这样写
function MyClass(){
}
MyClass.prototype.aFunction(){
}
var instance = new MyClass();
instance.aFunction();
3 带属性和方法的Class
function MyClass () {
//reference to this
var self = this;
//private member variable
var privateVar = "My Private Variable";
//public member variable
this.publicVar = "My Public Variable";
//private member function
var privateFunction = function () {
self.publicVar += " Modified By A Private Fucntion";
alert( self.publicVar );
}
}
//create an instance
var oClass = new MyClass();
//run a private member function
oClass.privateFunction(); //private function is undefined
//get a private member var
alert( oClass.privateVar ); //private var is undefined
4 带静态变量和静态方法的Class:
function MyClass () {
//...
}
//declare a static member
MyClass.staticVar = "My static variable";
//declare a static function
MyClass.staticFunction = function ( pInput ) {
return new MyClass( MyClass.staticVar , pInput );
}
//create an instance
var oClass = new MyClass();
//run a static function (NO access to private or public)
oClass.staticFunction( 9 ); //staticFunction is undefined on an instance
//run a privileged member function on the class
MyClass.privilegedFunction(); //The function runs
5 带特权(privileged)变量和方法的Class:
function MyClass () {
//private member variable
var privateVar = "My Private Variable";
//privileged member function
this.privilegedFunction = function () {
alert( privateVar );
}
}
//create an instance
var oClass = new MyClass();
//run a privileged member function
oClass.privilegedFunction(); //Output: alerts the value of the private var