您的位置:首页 > Web前端 > JavaScript

JS实例属性和原型属性的区别 (转自 zhs077)

2018-01-17 19:00 232 查看
第一种方式会对每一个类的方法和属性独立开辟一块内存空间,而原型链的方式则仅仅是引用

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 ;//删除原型中的属性
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: