关于前端开发中的构造函数模式和原型模式

来源:互联网 发布:ifunbox mac 破解版 编辑:程序博客网 时间:2024/06/15 19:56


我们都知道在新建一个函数的时候,会自动创建一个该函数的prototype,其中也会自动增加一个constructor属性;每次new一个函数的对象时,都会重复创建这个函数中的方法。


但是在这里就存在两个问题,每个实例对于函数中初始化的内容都是一样的,如果你想在一个实例中获得只有这个实例才存在的属性该如何实现??

如何解决函数中的方法重复创建的问题??


问题1解决方法:在创建这个函数的实例之后,通过对象来添加。

问题2解决方法:函数每个实例都会共享这个函数中prototype中的属性和方法;所以我们可以通过在函数的prototype中添加重复创建的方法即可。


下面是我实现的例子:

function Person(name,age) {
  this.name = name;
  this.age = age;
  this.friends = ["sheele","court"]
}


Person.prototype = {
  constructor:Person,
  test:function() {
    alert("success");
  }
};


var p1 = new Person("nich","12");
var p2 = new Person("cisf","33");


p1.friends.push("alice");
console.log(p1.friends);
console.log(p2.friends);


console.log(p1.friends === p2.friends);
console.log(p1.test === p2.test);



结果:

Array["sheele","court","alice"]

Array["sheele","court"]

false

true


阅读全文
1 0