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

对js 面对对象编程的一些简单的理解

2016-07-27 16:30 387 查看
由简单开始深入:

最简单的 直接对象开始

var desen = {
age:24,
name:'xyf',
job:'fontEnd',
getName:function(){
console.log(this.name);
},
setName:function(name){
this.name = name;
}
}


这是一个简单的对象实例。但是如果我要创建多个实例,将会非常麻烦。

改进写法:使用我们经常听到的构造函数模式。(构造函数的取名默认首位大写)

function Desen(age,name){
this.age = age;
this.name = 'name';
this.getName=function(){
console.log(this.name);
}
this.setName=function(name){
this.name = name;
}
}


使用构造函数的好处有很多。一来可以方便的创建多个实例,二来可以清楚的知道他们的原型对象(实例拥有[code]constructor
属性,指向他们的构造函数)

再进一步:如果我们有很多实例了,但是每个实例中有重复包含了setNameh 函数 非常浪费内存。这里就要引用到耳熟能详的原型概念了--Prototype.
继续修改之前的构造函数[/code]

function Desen(age,name){
this.age = age;
this.name = 'name';
this.getName=function(){
console.log(this.name);
}
}
Desen.prototype.setName = function(name){
this.name  = name;
}


这种写法,将之前每个实例都拥有的相同功能简化为一个。存于prototype对象中。至于为何(参考js原型链)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: