您当前的位置: 首页 > 学无止境 > JS经典实例 网站首页JS经典实例
javascript对象与原型-构造函数、对象冒充与引用类型
发布时间:2016-10-16 13:41:58编辑:雪饮阅读()
构造函数创建对象:
function Box(name,age){
this.name=name;
this.age=age;
this.run=function (){
return this.name+this.age+"运行中";
}
}
var box1=new Box('聂风',24);
var box2=new Box('步惊云',24);
alert(box1.run());
alert(box2.run());
构造函数创建对象特点:
1、不需要再函数末尾返回对象引用他是自动返回的
2、构造函数函数名第一个字母必须大写
3、使用构造函数实例化对象,必须new函数名,构造函数普通调用无效
4、构造函数创建对象可以识别实例化所属对象,如:
function Box(name,age){
this.name=name;
this.age=age;
this.run=function (){
return this.name+this.age+"运行中";
}
}
function Desk(name,age){
this.name=name;
this.age=age;
this.run=function (){
return this.name+this.age+"运行中";
}
}
var box1=new Box('聂风',24);
var box2=new Box('步惊云',24);
var box3=new Desk('秦霜',24);
alert(box1 instanceof Box);
alert(box2 instanceof Box);
alert(box3 instanceof Box);
构造函数相当于改良后的工厂模式
对象冒充:
function Box(name,age){
this.name=name;
this.age=age;
this.run=function (){
return this.name+this.age+"运行中";
}
}
var mc=new Object();
Box.call(mc,'盗版',0);//对象冒充,使得mc对象拥有了Box的所有属性和方法
alert(mc.run());
引用类型:
function Box(name,age){
this.name=name;
this.age=age;
this.run=function (){
return this.name+this.age+"运行中";
}
}
var box1=new Box('雪饮',24);//实例化地址为1
var box2=new Box('雪饮',24);//实例化地址为2
alert(box1.run()==box2.run());
alert(box1.run==box2.run);
//box1.run()==box2.run(),这是比较的两个方法的返回值
//box1.run==box2.run,这是比较的引用地址,而box1与box2的引用地址不同,所以会返回fal
以上示例代表了这实例化出来的变量是引用类型,既然是引用类型,那么Box构造函数还可以这样:
function Box(name,age){
this.name=name;
this.age=age;
this.run=new Function("return this.name+this.age+'运行中。。。'");
}
var box1=new Box('雪饮',24);
alert(box1.run());
实现引用地址一致:
function Box(name,age){
this.name=name;
this.age=age;
this.run=run;
}
function run(){
//把构造函数内部的方法通过全局来实现引用地址一致
return this.name+this.age+"运行中";
}
var box1=new Box('雪饮',24);
var box2=new Box('雪饮',24);
alert(box1.run==box2.run);
这样可以实现引用地址的一致性,但是有个问题:
全局中的this在对象调用时候是Box本身,而当作普通函数调用时候this又代表windows,这样很不好,可以被外部随便乱用。
关键字词:javascript,对象,原型