提筆忘字啊,今天突然要用到jS,發現有很多東西已經不是記得很牢,怪就怪在以前不好好整理所學內容,這裏先整理一點點
基本方法的定義:
方式一:
<script language="javascript">
function fun() // 普通方法定義
{
alert("call fun");
}
fun();
</script>
方式二:
<script language="javascript">
var fun = function() // 定義方法爲變量
{
alert("call fun");
}
fun();
var temp = fun; // 方法以變量的方式傳遞
temp();
alert(temp);
</script>
方式三:
<script language="javascript">
var fun = new Function("var temp = 100; this.temp = 200; alert('temp + this.temp = ' + (temp + this.temp));");
// 注意temp 與 this.temp 區別
fun();
</script>
類方法:
一、公開方法和內部方法:
<script language="javascript">
function Person(name,iage,sal){
this.name=name; // 僅有屬性
var age=iage; // 私有屬性
var salary=sal;
this.show=function(){ //公開方法(特權方法)
window.alert(name + age+" "+salary);
}
function show2(){ //私有方法(內部方法) 類體內使用
window.alert(name + age+" "+salary);
}
this.showshow=function(){
show2();
}
}
var person = new Person("張良", 30, 30000);
person.show();
//person.show2(); // ERROR
person.showshow();
</script>
二、通過prototype 定義類公有方法:
<script language="javascript">
function Dog(){
}
Dog.prototype.shout=function(){ // 通過prototype 定義類方法
window.alert("小狗");
}
var dog1=new Dog();
dog1.shout();
var dog2=new Dog();
dog2.shout();
window.alert(dog1.shout==dog2.shout); //共用函數,地址一樣可看出
</script>
三、方法的覆寫:
<script language="javascript">
//學生類
function Student(name,age){
this.name=name;
this.age=age;
this.show=function(){
window.alert(this.name+" "+this.age);
}
}
function MidStu(name,age){
this.stu=Student;
this.stu(name,age); //js實際上是通過對象冒充實現繼承
//MidStu可以覆蓋Stu類的show
this.show=function(){
window.alert("MidStu show()");
}
}
var midStu=new MidStu("宋江",40);
midStu.show();
</script>