提笔忘字啊,今天突然要用到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>