javascript 对象

2020-11-22  本文已影响0人  张晖

创建对象的三种方法:

字面量 obj = {}、obj = new Object()、构造函数

字面量方法创建对象:


let obj ={
  uname:'Jack',
  age:28,
  sayHi:function(){
    console.log('Hi!');
  }
}

使用对象

// 接上面代码
console.log(obj.uname);   // Jack
console.log(obj['age']);   // 28
obj.sayHi();   // Hi!

new Object() 创建对象


let obj = new Object();
obj.uname = 'Tom'; 
obj.age = 36; 
obj.sayHi = function(){
  console.log('Hi~');
}

console.log(obj.uname); // Tom
console.log(obj['age']); // 36
obj.sayHi(); // Hi~

使用构造函数创建对象


代码实例:

function Star(uname, age, gender) {
    this.uname = uname;
    this.age = age;
    this.gender = gender;
    this.sayHi = function(msg){
        console.log('Hi~'+msg)
    }
}
let p1 = new Star('Jack', 28, 'male');
let p2 = new Star('Lily', 23, 'female');
console.log(p1.uname);  // Jack
console.log(p1['age']);  // 28
console.log(p2.gender);  // female
p1.sayHi('how are you!'); // HI~ how are you!

构造函数的特点

new 关键字的执行过程

for ... in 遍历对象

let obj = {
    uname: 'Jack',
    age: 28,
    gender: 'male',
    sayHi: function() {
        console.log('Hi~');
    }
}
for (let key in obj) {
    console.log(key + ':' + obj[key]);
}

小结

上一篇 下一篇

猜你喜欢

热点阅读