含义
- 对象只是一种特殊的数据,对象是一个包含相关数据和方法的集合(通常由一些变量和函数组成,我们称之为对象里面的属性和方法)
- 语法(objectname 对象名字,大括号内的为对象的属性和方法)
var objectName = {
member1Name : member1Value,
member2Name : member2Value,
member3Name : member3Value
}
对象的属性和方法
- 属性是与对象相关的值
- 对象成员的值可以是任意的,在对象里有字符串(string),数字(number),数组(array),函数(function)。
- 对象的属性(property)
字符串(string),数字(number),数组(array) - 对象的方法(method)
函数(function)
访问对象属性的方法
objectName.propertyName // 语法
1.点表示法(dot notation)
name : ['Bob', 'Smith'],
name : {
first : 'Bob',
last : 'Smith'
},
person.name.first
person.name.last
2.括号表示法(bracket notation)
person.age
person.name.first
person['age']
person['name']['first']
访问对象方法的方法
objectName.methodName() // 语法
var message="Hello world!";
var x=message.toUpperCase(); //使用了 String 对象的 toUpperCase() 方法来将文本转换为大写
设置对象成员/属性
创建属性的值
1.非动态创建
person['eyes'] = 'hazel'
person.farewell = function() { alert("Bye everybody!") }
<script>
var user = { name:'jhon',surname:'mike'}
</script>
<script>
var person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
document.write(person.firstname + " is " + person.age + " years old.");
</script>
<script>
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}
document.write(person.firstname + " is " + person.age + " years old.");
</script>
2.动态创建
var myDataName = nameInput.value
var myDataValue = nameValue.value
var person = {
var myDataName = 'height'
var myDataValue = '1.75m'
person[myDataName] = myDataValue}
3.使用对象构造器
<script>
function person(firstname,lastname,age,eyecolor){
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
myFather=new person("John","Doe",50,"blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");
</script>
更新已经存在的属性的值
属性更改
person.age = 45
person['name']['last'] = 'Cratchit'
var user = { name:'jhon',surname:'mike'}
user['name'] = 'peter'
delete user.name
person.firstname="John";
person.lastname="Doe";
person.age=30;
person.eyecolor="blue";
x=person.firstname;
方法更改
<script>
function person(firstname,lastname,age,eyecolor){
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.changeName=changeName;
function changeName(name){
this.lastname=name;
}
}
myMother=new person("Sally","Rally",48,"green");
myMother.changeName("Doe");
document.write(myMother.lastname);
</script>
"this"
关键字"this"指向了当前代码运行时的对象,保证了当代码的上下文(context)改变时变量的值的正确性