对象字面量创建对象
var person={
name:"Nicholas",
age:29,
job:"SE",
sayName:function(){
alert(this.name);
}
};
属性类型
[configrurable]:表示可否通过delete删除属性从而重新定义属性 默认 true;
[Enumerable]:表示可否通过for-in循环返回属性 默认true
[Writable]:表示可否修改属性的值;默认true
[Value]:包含这个属性的数据值。默认undefined
例如
var person=();
Object.defineProperty(person."name",{
writable:false,
value:"Nicholas"
});
alert(person.name);//"Nicholas"
person.name="Greg";
alert(person.name);//"Nicholas"
//在这个程序中name属性是只读的;
访问器属性
[configrurable]:表示可否通过delete删除属性从而重新定义属性 默认 true;
[Enumerable]:表示可否通过for-in循环返回属性 默认true
[Get];表示在读取属性时调用的函数。默认值为undefined
[Set]:在写入属性时调用的函数。默认值为undefined
访问器属性需要通过Object.defineProperty()来定义
var book=(
_year:2004,
edition:1
);
Object.defineProperty(book,"year",{
get:function(){
return this._year;
},
set:function(){
if(newValue>2004){
this._year=newValue;
this.edition+=newValue-2004;
}
}
}
book.year=2005;
alert(book.edition);//2
工厂模式
由于在ECMAScript中无法创建类,开发人员发明了一种函数
用函数来封装。
function createPerson(name,age,job)
{
var o=new Object();
o.name=name;
o.job=job;
o.sayName=function(){
alert(this.name);
};
return 0;
}
var person1=creatPerson("Nicholas",29,"SE");
构造函数模式
例子
function Person(name,age,job){
this.name=name;
this.age=age;
this.job=job;
this.sayName=function(){
alert(this.name);
};
}
var person1=new person("Nicholas",29,"SE");
任何函数只要通过new操作符来调用,那么他就可以作为构造函数;
//当构造函数来使用
var person=new person("Nicholas",29,"SE");
person.sayName();//"Nicholas";
//作为普通函数调用
peson("Greg",23,"D");//添加到了window
window.sayName()://"Greg"
理解
继承
function People(){
}//创建一个类
People.prototype.say=function(){
alert("hello");
}
function Student(){
}
Student.protype=new People(){
}
var s=new Student();
s.say();//继承,
function People(){
}//创建一个类
People.prototype.say=function(){
alert("hello");
}
function Student(){
}
Student.protype=new People()
Student.prototype.say=function(){
alert("stu-hello");//复写方法
}
var s=new Student();
s.say();//继承,在复写后显示子类