关于前端开发中的构造函数模式和原型模式
2017-08-27 10:50
253 查看
我们都知道在新建一个函数的时候,会自动创建一个该函数的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解决方法:在创建这个函数的实例之后,通过对象来添加。
问题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
相关文章推荐
- web前端开发中关于面向对象(三)
- 关于软件公司开发模式的思考
- 谈谈关于前端开发网页适配手机的相关设置
- 关于开发模式的一点点思考
- noBackend:前端优先的开发模式
- 前端学习心得-javascript设计模式与开发实践-命令封装模式
- 【JCP模式实战--ferrous-framework】ferrous前端开发框架邀您初体验
- 关于前端组件化开发的一点思考
- 收藏的一些关于web前端开发的资源(很强大,种类很多)
- 关于提高开发效率的面向对象开发模式的思考
- 前端开发常见问题之Swiper.js的loop模式下,如何正确获取索引值?
- 关于前端开发需要必备的常识
- <转>前端开发中的MCRV模式
- 关于Exchange 2010前端服务器的高可用模式!
- 关于前端开发中的“收口”思想
- 关于前端开发中的“收口”思想
- 关于前端开发的20篇文档与指南
- 浅析前端开发中的 MVC/MVP/MVVM 模式
- 关于php mvc开发模式的感想
- 关于前端开发的思考