初学JS,总结一下JS创建对象的几种方法
例如创建一个student对象,属性有age和name,方法是show age和name
一、直接创建
var obj = {‘属性名1’:值1,
‘属性名2’:值2,
‘功能名1’:function(){…},
};
属性中的引号可以去掉
<pre>
var student = {
name : "wangmeng",
age : 12,
showInfo : function showInfo() {
// body...
alert("wo jiao"+this.name+"jinnian"+this.age)
}
}
student.showInfo()
</pre>
二、先创建一个空对象
<pre>
var student = Object()
student.name = "wangmeng"
student.age = 12
student.showInfo = function(){
alert("wo jiao"+this.name+"jinnian"+this.age)
}
</pre>
三、构造器创建
<pre>
function Student(name,age){
this.name = name
this.age = age
this.showInfo = function() {
alert("I am"+name+",today"+age)
}
}
</pre>
var wangmeng = new Student("wangming",12)
wangmeng.showInfo()
四、动态构造
JS继承:
js中一切继承都是用原型对象实现的!
原型对象:每个函数对象都有一个原型对象
构造函数的原型对象负责保存所有子对象共享的成员
建议:所有子对象共享的方法,都应该定义在构造函数的原对象中。——避免重复定义方法对象,浪费内存。
说明:其实所有内置类型的API都是定义在类型.prototype
扩展对象属性:2种展
1.扩展共有属性:通过构造函数.prototype添加的属性
2.扩展自有属性: 通过某一个具体子对象添加的属性
如果判断是自有属性还是共有属性
1.判断自有属性:obj.hasOwnProperty(属性名)
2.判断共有属性: “属性名” in obj && !obj.hasOwnProperty
<pre>
function Student(name,age){
this.name = name
this.age = age
}
Student.prototype.showInfo = function() {
alert("I am "+this.name+" and this year"+this.age+" years old")
}
var lilei = new Student("lilei",12)
var hmm = new Student("hmm",14)
Student.prototype.money = 100
Student.prototype.money -= 20
hmm.banfei = 10
</pre>
五、Object.create(父对象,{扩展属性的列表对象})
<pre>
var student = Object.create({name:"wangmeng",age:12})
</pre>












网友评论