1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > javascript 原型属性(prototype 属性)与 实例属性(自身属性)

javascript 原型属性(prototype 属性)与 实例属性(自身属性)

时间:2023-12-12 15:59:49

相关推荐

javascript  原型属性(prototype 属性)与 实例属性(自身属性)

讲到原型属性,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);//trueconsole.log(box1.run() == box2.run());//trueconsole.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); //trueconsole.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:

通过上面的例子可以看出,我在实例方法中照样可以访问下面所定义的原型属性的值。

参照资料:

/topic/518a3adc63e9f8a5420df3b4

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。