TODO:这里的用法没有达到完备的程度,要继续修订、增添。
面向对象地使用JavaScript, 一例胜千言. 能用就先用着吧.
面向对象地使用JavaScript, 一例胜千言. 能用就先用着吧.
//定义一个类People, 类中包含一个字串变量name, 和一个方法display.
function People(){
this.name = "default";
this.display = function(){
return "People's name is " + this.name;
};
}
//由类People来创建一个对象aPeople, 并调用对象的方法display().
var aPeople = new People();
alert("Simply invoke a method in an object: " + aPeople.display());
//============================================
//创建继承了People类的AnotherPeople类.
var AnotherPeople = new Function();//这里的"Function"暂不能理解, 但不影响使用.
AnotherPeople.prototype = new People();//AnotherPeople类在这里对People类进行继承.
var finalPeople = new AnotherPeople();
alert("User father's method: " + finalPeople.display());
finalPeople.display = function(){
//在对象里覆写父类中的方法.
return "finalPeople is inherited successfully.";
};
alert(finalPeople.display());
//=============================
var OverRidePeople = new Function();
OverRidePeople.prototype = new People();
OverRidePeople.prototype.display = function(){
//在新类中覆写父类中的方法. 这是我需要的用法.
return "OverRidePeople is here";
};
var oneOverRidePeople = new OverRidePeople();
alert("Method override: " + oneOverRidePeople.display());
//=============================
//类Manager里包含了上面定义的类People的对象.
function Manager(){
//要做一件事情, 先定义一个类, 让这个类的对象来完成事情.
this.onePeople = new People();
this.display = function(){
return "Manager's name is " + this.onePeople.name;
};
}
var aManager = new Manager();
alert(aManager.display());
//===============================
//回调函数的使用.
function method(){
alert("This is method.");
}
function trigger(inputMethod){
inputMethod();
}
trigger(method);