javaScript闭包
<script type="text/javascript">
function father(){
var a = 2;
function child(){
alert(a++);
}
return child;
}
var result = father();
result();
通过方法中的方法 调用 外部方法的私有属性 ,外部方法在将内部方法(对象)返回;
<script type="text/javascript">
var name = "window object";
var object = {
name : "my object",
getNameFunc : function(){
var name = "my Function Object";
return function(){
return this.name;
};
}
};
//alert(object.name);
alert(object.getNameFunc()());
</script>
JavaScript 创建对象
1.对象初始化器
<script type="text/javascript">
var marry = {
name : 'marry',
age : 12,
shout : function(){
alert(this.name + "今年,"+this.age+"岁了");
},
action : function(){
alert('睡觉');
},
};
alert(marry.name);
alert(marry.age);
marry.shout();
marry.action();
</script>
2.构造方法
<script type="text/javascript">
function Dog(name,age){
this.name = name;
this.age = age;
this.shout = function(){
alert("我是"+this.name+",今年"+this.age+"岁了");
};
this.action = function(){
alert("吃饭");
}
}
var jack = new Dog("jack", 100);
alert(jack.name);
alert(jack.age);
jack.shout();
jack.action();
</script>
3.对象属性
<script type="text/javascript">
function C(){
this.objectPro = "对象属性";
C.prototype.objectPro2 = "对象属性2";
}
C.classPro = "类属性";
alert(C.classPro);
var c = new C();
alert(c.objectPro);
alert(c.objectPro2);
</script>
4.对象方法
<script type="text/javascript">
function C() {
var privateFunc = function() {
alert("私有方法");
};
privateFunc();
this.objectFunc1 = function() {
alert("对象方法");
};
C.prototype.objectFunc2 = function() {
alert("对象方法2");
};
}
C.classFunc = function() {
alert("类方法")
}
C.classFunc();
var c = new C();
c.objectFunc1();
c.objectFunc2();
</script>
5.1. 继承属性和方法 apply
<script type="text/javascript">
function Animal(name,age){
this.name = name;
this.age = age;
this.shout = function(){
alert("我是"+this.name+",今年"+this.age+"岁了");
};
this.action = function(){
alert("吃饭");
}
};
function Dog(name,age){
Animal.apply(this, [name,age]);
};
var tom = new Dog('tom', 111);
alert(tom.name);
alert(tom.age);
tom.action();
tom.shout();
</script>
5.2. 原型的继承 Prototype;
<script type="text/javascript">
function Animal(name,age){
this.name = name;
this.age = age;
this.shout = function(){
alert("我是"+this.name+",今年"+this.age+"岁了");
};
this.action = function(){
alert("吃饭");
}
};
function Dog(name,age){
Animal.apply(this, [name,age]);
};
Dog.prototype = new Animal();
var tom = new Dog('tom', 111);
alert(tom.name);
alert(tom.age);
tom.action();
tom.shout();
</script>
6.javaScript实现多态
<script type="text/javascript">
function Animal(){
this.say = function(){
alert("我是动物");
};
}
function Dog(){
this.say = function(){
alert("我是狗");
};
}
Dog.prototype = new Animal();
function Cat(){
this.say = function(){
alert("我是猫");
};
}
Cat.prototype = new Animal();
function say(animal){
if(animal instanceof Animal){
animal.say();
}
}
var dog = new Dog();
var cat = new Cat();
say(dog);
say(cat);
</script>