- object
- Three ways to create an object: ① object literal ② new Object() ③ constructor, new constructor()
- new keyword
- iterate over object properties
1. Create an object
1. Create objects using object literals
//1.利用字面量创建对象
var obj ={
uname: '小明',
age:18,
sex:'男',
sayHi:function(){
console.log('hi')
}
}
//调用对象的属性
console.log(obj.sayHi)
console.log(obj['age'])
//调用对象的方法
obj.sayHi()
①The attribute values inside are in the form of key-value pairs, key attribute name: value attribute value
The method colon is followed by an anonymous function
② Object used: object name. attribute name
ObjectName['PropertyName']
ObjectName.MethodName()
2. Variables, properties, functions, methods
①Variable: declare and assign value separately, directly write the variable name to exist alone when using it
②Properties: In the object, there is no need to declare, and the object.property must be used when using
③Function: It is declared separately, and calls the function name (), exists alone
④ Method: In the object, when calling object. method ()
⑤Constructor: generally refers to a certain category, which is similar to the class in java
⑥Object: specifically refers to a specific thing Andy Lau=={name:'Andy Lau',age:18………}
3. Use new Object to create objects
//利用new object创建对象
var obj = new Object()
obj.age = 18
obj.name = '男'
obj.sayHello = function(){
console.log('hello');
}
console.log(obj.age);
obj.sayHello()
4. Create objects using constructors
The previous two methods of creating objects can only create one object at a time
The constructor is to abstract the same properties and methods in the object and encapsulate them in the function
Grammar format:
function star(uname,age,sex){
this.name = uname
this.age = age
this.sex = sex
this.sing = function(song){
console.log(song);
}
}
var ldh = new star('刘德华',18,'男')
console.log(ldh.name)
console.log(ldh['sex'])
ldh.sing('冰雨')
console.log(typeof(ldh))
Notice:
1. The first letter of the constructor name should be capitalized (customary)
2. The constructor can return the result without return
3. Calling the constructor must use new
4. We create an object ldh{} as long as new Star() calls the function
5. Using constructors to create objects is also called object instantiation
2. Keyword new
1. New keyword execution process
①The new constructor creates an empty object in memory
②this will point to the empty object just created
③ Execute the code in the constructor and add properties and methods to this empty object
④Returning this object is also the reason why you don’t need to write return
Third, traverse the object properties
for(var k in ldh){
console.log(k); //k,输出的是属性名
console.log(ldh[k]); //k是个变量,不加引号
}
Output :