ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
对象主要具有:行为——方法,特征——属性。 [TOC] # 1. 对象的创建 <mark>语法1:字面量语法</mark> ```js // 创建 var object = { name: 'zs', age: 18, sex: true, sayHi: function () { console.log(this.name); } }; // 调用 object.name; // 或object["name"] object.sayHi(); // 或object["sayHi"] ``` <mark>语法2:new Object()方式</mark> ```js // 创建 var person = new Object(); person.name = 'lisi'; person.age = 35; person.job = 'actor'; person.sayHi = function(){ console.log('Hello,everyBody'); } // 调用 person.name; // 或 person["name"] person.age; // 或 person["age"] person.sayName; // 或 person["sayName"] ``` <mark>语法3:工厂函数</mark> ```js function createPerson(name, age, job) { var person = new Object(); person.name = name; person.age = age; person.job = job; person.sayHi = function(){ console.log('Hello,everyBody'); } return person; } var p1 = createPerson('张三', 22, 'actor'); ``` 或者: ``` function createPerson (name, age) { return { name: name, age: age, sayName: function () { console.log(this.name) } } } ``` <mark>语法4:自定义构造函数</amrk> ```js function Person(name,age,job){ this.name = name; this.age = age; this.job = job; this.sayHi = function(){ console.log('Hello,everyBody'); } } var p1 = new Person('张三', 22, 'actor'); ``` 更好的对象创建方法见:12.4章。 # 2. 对象的遍历与删除 <mark>1. 使用for/in语句遍历对象</mark> ```js var obj = {}; for (var i = 0; i < 10; i++) { obj[i] = i * 2; } for(var key in obj) { console.log(key + "==" + obj[key]); } ``` <mark>2. 删除对象</mark> ```js function Fun() { this.name = 'mm'; } var obj = new Fun(); console.log(obj.name); // mm delete obj.name; console.log(obj.name); // undefined ```