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

javascript--面向对象(三)原型对象存在的问题及组合组合使用原型和构造函数

2017-06-19 21:29 603 查看

1、原型对象存在的问题

原型的概念:原型对象里所有的属性和方法被所有的构造函数实例化的对象共享

原型里的属性和方法被实例共享,static 修改属性和方法,所有对象都被修改

function Person(){

}

Person.prototype = {
constructor:Person,
name:"z3",
age:20,
friends:['里4','王5'],
sayName : function(){
console.info("mingzi");
}
}

var p1 = new Person();
var p2 = new Person();
//p1加入一friends
p1.friends.push('赵6');

console.info(p1.friends);//["里4", "王5", "赵6"]
console.info(p2.friends);//["里4", "王5", "赵6"]




2、解决方法:组合使用原型和构造函数式  :开发时常用的方式  用的最多的

function Student(name,age,friends,job){
this.name = name;
this.age = age;
this.friends = friends;
this.job = job;
}

Student.prototype = {
constructor :Person,
sayName : function(){
console.info(this.name);
}
}

var s1 = new Student('linag',20,['ni','li','k2'],'开发');
var s2 = new Student('chang',40,['m2','j1'],'老本');

console.info(s1.friends);// ["ni", "li", "k2"]
console.info(s2.friends);//["m2", "j1"]


注意要重新将原型对象的constructor定义为构造函数

Student.prototype = {
constructor :Person,//注意要重新将原型对象的constructor定义为构造函数
sayName : function(){
console.info(this.name);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐