讲到原型属性,prototype属性,实例属性,自身属性,首先我们要明白这四者之间的关系。我查了一些资料,原型属性又叫prototype属性,实例属性又叫自身属性。只是叫法不同。下面我要引用他人写的一段代码来加以说明:
1:实例属性指的是在构造函数方法中定义的属性,属性和方法都是不一样的引用地址例如:
function CreateObject(name,age){
this.name=name; //实例属性
this.age=age;
this.run=function(){ //实例方法
return this.name + this.age;
}
//可以设置全局方法来实现引用地址一致性 .会出现问题
//this.run = run;
}
var box1 = new CreateObject('ZHS',100);
var box2 = new CreateObject('ZHS',100);
console.log(box1.name == box2.name);//true
console.log(box1.run() == box2.run());//true
console.log(box1.run == box2.run); //false 比较的是引用地址
如何让box1,和box2run方法的地址一致呢?使用冒充
例如:
//对象冒充
var o = new Object();
Box.call(o,'xlp',200);
console.log(o.run());
2.原型属性指的是不在构造函数中定义的属性,属性和方法都是一样的引用地址,例如
function CreateObject(){}
CreateObject.prototype.name='ZHS';
CreateObject.prototype.age='100';
CreateObject.prototype.run=function(){
return this.name + this.age;
}
var CreateObject1 = new CreateObject();
var CreateObject2 = new CreateObject();
console.log(CreateObject1.run == CreateObject2.run); //true
console.log(CreateObject1.prototype);//这个属性是个对象,访问不了
console.log(CreateObject1.__proto__);//这个属性是个指针指向prototype原型对象
console.log(CreateObject1.constructor);//构造属性
如果我们在CreateObject1 添加自己属性呢?例如
CreateObject1.name='XLP';
console.log(CreateObject1.name);// 打印XLP //就近原则
可以使用delete删除实例属性和原型属性
delete CreateObject1.name; //删除实例中的属性
delete CreateObject.prototype.name ;//删除原型中的属性
为了更进一步说明prototype属性,在此我再增加一段代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function employee(name,age,address){
this.name=name;
this.age=age;
this.address=address;
this.hello=function(){
return "名字:"+this.name+";"+"年龄:"+this.age+";"+"地址:"+this.address;
}
}
var employ1=new employee("小欧",23,"浙江衢州");
employee.prototype.country="中国";
document.write(employ1.country);
document.write("<br>");
document.write(employ1.hello());
</script>
</body>
</html>
ouput:
中国
名字:小欧;年龄:23;地址:浙江衢州
实例化的对象可以共享原型对象的所有属性与方法。
例子如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function createPerson(name,age,address){
this.name=name;
this.age=age;
this.address=address;
this.sayname=function (){
return this.sex;
}
}
createPerson.prototype.sex="女";
var Obj=new createPerson("xiaohong",25,"武汉");
document.write(Obj.sex);
document.write("<br>");
document.write(Obj.sayname());
</script>
</body>
</html>
output:
女
女
通过上面的例子可以看出,我在实例方法中照样可以访问下面所定义的原型属性的值。
参照资料: