面向对象地使用JavaScript

TODO:这里的用法没有达到完备的程度,要继续修订、增添。

面向对象地使用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);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值