/*---------------------js闭包--------------------*/
//这个函数内部的一个变量能够在函数外面被引用时,我们就称创建了一个闭包
function add(a) {
var i = 0;
return function(b) {
alert("c"+a);
return a+b;
}
}
var func = add(10);
alert("a" +func); //return function(b) {alert("c"+a); return a+b;}
alert("b"+func(2)); //12
/*----------------------------------------------*/
function Person() {
var id = 4444;
this.getId = function() {
return id;
}
this.setId = function(newId) {
id = newId; //1000
}
/* this.__defineGetter__("id", function () {
return id;
}); //去掉 */
}
var p = new Person();
alert(p.prototype);
alert(p.id); // ?undefined
p.setId(1000);
alert(p.getId()); // ?1000
alert(p.id); // ? undefined
/*----------------------------------------------*/
//函数无重载 有重写
function doadd(nu) {
alert(nu+10);
}
function doadd(nu2,al2) {
alert(al2);
alert(nu2+1);
}
doadd(10);//11
/*--------------prototype------------------*/
//理解prototype不应把它和继承混淆。A的prototype为B的一个实例,可以理解A将B中的方法和属性全部克隆了一遍。A能使用B的方法和属性。这里强调的是克隆而不是继承。可以出现这种情况:A的prototype是B的实例,同时B的prototype也是A的实例
function People(name){
this.name=name;
this.aa=12345;
//对象方法
this.Introduce=function(){
alert("My name is "+this.name);
return "My name is yy";
}
}
//类方法
People.Run=function(){
alert("I can run");
}
//原型方法
People.prototype.IntroduceChinese=function(){
//克隆People对象属性
alert("我的名字是"+this.name);
//克隆People对象方法
alert("aa------------"+this.Introduce());
}
//测试
var p1=new People("Windking");
p1.Introduce(); //My name is Windking
People.Run(); //I can run
p1.IntroduceChinese(); //我的名字是Windking
//2克隆方法
function baseClass(){
this.showMsg = function(){
alert("baseClass::showMsg");}
}
function extendClass(){
}
extendClass.prototype = new baseClass();
var a = new extendClass();
a.showMsg(); // 显示baseClass::showMsg
js闭包、prototype
最新推荐文章于 2021-11-19 09:37:47 发布