文章知识点比较多,建议拷贝代码,逐一去除alert注释琢磨参透。如果有单一疑问请自己参考javascript文档!
基本操作方法
function Box(){ this.test="test"; }; Box.prototype.username="jet"; Box.prototype.age=29; Box.prototype.run=function(){ return this.username+this.age+"岁发大财"; }; var boxa=new Box(); var boxb=new Box(); //alert(boxa.run==boxb.run); //指向相同 //alert(boxa.prototype); //无法访问 undefined //alert(JSON.stringify(boxa.__proto__)); //指针指向Box prototype //alert(boxa.__proto__.run()); //可运行 //alert(boxa.constructor); //构造函数本身Box //alert(boxa.constructor.prototype.run()); var boxc=new boxa.constructor; //alert(boxc.run()); //可运行 //alert(boxc instanceof Box); //true boxa.username='chow'; //alert(boxa.username); //就近原则,不读指针原型 delete boxa.username; //删除实例属性,就读原型属性 //alert(boxa.username); //删除实例属性,就读原型属性 //alert(boxa.hasOwnProperty("username")); //判断是否存在指定的实例属性,如果上方执行了delete就返回false //alert("username" in boxa); //判断实例或者原型是否包含指定属性。无论实例还是原型有,都会返回true
//判断是否只有对象原型是否包含指定属性 function isproperty(object,username){ return !object.hasOwnProperty(username) && username in object; } //alert(isproperty(boxa,"username")); //boxa.kk='kk'; //alert(isproperty(boxa,"kk"));
|
prototype原型对象化
//prototype原型对象化 function Boxtwo(){}; Boxtwo.prototype={ username:"jet", age:29, run:function(){ return this.username+this.age+"岁发大财"; }, } var Boxtwoa = new Boxtwo(); //alert(Boxtwoa.run());
//构造函数 + prototype原型混合使用 function Boxthree(username,age,doing){ this.username=username; this.age=age; this.doing=doing; if(typeof Boxthree.prototype.run != "function"){ //判断是否初始化话原型 //alert("初始化原型"); Boxthree.prototype.run=function(){ return this.username+this.age+this.doing; }; } }; var Boxthreea = new Boxthree("jet",29,"岁发大财"); var Boxthreeb = new Boxthree("chou",30,"岁行大运"); var Boxthreec = new Boxthree("baby",5,"岁了,身体越来越棒!"); // alert(Boxthreea.run()); // alert(Boxthreeb.run()); // alert(Boxthreec.run());
|
原型链继承
//原型链继承 function Boxfour(){ this.username="jet"; this.age=29; }; Boxfour.prototype.run=function(){ return this.username+this.age+"岁发大财"; }; function Boxfive(){}; Boxfive.prototype=new Boxfour(); //Boxfive原型继承了Boxfour的构造属性和原型属性 var Boxfivea = new Boxfive(); //alert(Boxfivea.username) //jet 继承成功 //alert(Boxfivea.run()) //正常运行 //alert(Boxfivea instanceof Boxfive); //true //alert(Boxfivea instanceof Boxfour); //true
//对象冒充继承 function Boxsix(username,age){ this.username=username; this.age=age; }; Boxsix.prototype.run=function(){ return this.username+this.age+"岁发大财"; }; function Boxseven(username,age){ Boxsix.call(this,username,age); }; var Boxsevena = new Boxseven("jet",29); //alert(Boxsevena.username);//jet //构造属性继承成功 //alert(Boxsevena.run);//undefined //对象原型prototype无法继承 //alert(Boxsevena instanceof Boxseven); //true //alert(Boxsevena instanceof Boxsix); //false Boxseven.prototype=new Boxsix(); //使用原型链继承run + 上面的对象冒充继承实例属性,则可以正常运行 var Boxsevenb = new Boxseven("jet",29); // alert(Boxsevenb.run()); //正常运行 |