对象
- 对象中的this 永远指向对象本身。
对象字面量,对象直接量
var teacher = {
name: '张三',
age: 20,
height: 177,
weight:120,
sex: 'male',
teach: function () {
console.log('i am teaching JavaScript');
},
smoke: function () {
this.weight--;
console.log(this.weight);
},
eat: function () {
this.weight++;
console.log(this.weight);
}
}
//这个teaacher 就是对象字面量。
var attendance = {
students: [],
total:6,
join: function (name) {
var idx = this.students.indexOf(name);
if (idx!==-1) {
console.log(name + '已经到了');
return
}
if (this.students.length === 6) {
console.log('已到齐');
return;
}
this.students.push(name);
},
leave: function (name) {
var idx = this.students.indexOf(name);
if (idx !== -1) {
console.log(name + '早退');
this.students.splice(idx, 1);
}
},
classOver: function () {
this.students = [];
}
}
构造函数
var obj = {};//对象字面量
var obj = new Object();//对象构造函数。
//以上两种方式创建的对象完全相同。
自定义构造函数
首字母都是大写。大驼峰。
- 构造器中的this 如果构造器没有实例化,就是没有意义。
- 构造器中的this在构造函数被实例化之后才有用。
function Teacher(opt) {
this.name = opt.name;
this.age = opt.age;
this.sex = opt.sex;
this.weight = weight;
this.smoke = function () {
this.weight--;
}
this.eat = function () {
this.weight++;
}
}
var teacherOne = new Teacher({
name: '张三',
age: 20,
sex: 'male',
weight:'130'
})
var teacherTwo = new Teacher({
name: '李四',
age: 21,
sex: 'female',
weight:'100'
})
demo
- 写一个构造函数,接受函数类型的参数,参数不定,完成参数相乘或相加。
- 写一个构造函数。可以设置车的品牌,颜色,排量。再写一个消费者的函数,设置用户的名字。年龄,收入。通过选车的方式。实例化改用户喜欢的车。再设置车的属性。
```javascriptfunction Count() {
var args = arguments;//实参
this.count = function () {
let num = 0;
for (let i = 0; i < args.length; i++) {
let val = args[i];
//不是number 类型就直接跳过
if (typeof (val) != 'number') {
continue
}
num += val;
}
console.log(num)
}
console.log(arguments);
}
var c = new Count(1, 2, 3, 4, 6);
c.count();
function Car(opt) { this.brand = opt.brand; this.color = opt.color; this.output = opt.output; } function Person(opt) { this.name = opt.name; this.age = opt.age; this.income = opt.income; this.selectCar = function () { var car = new Car(opt.carOpt) console.log(this.name + ‘ s favoriate car is ‘ + car.brand); } } var personA = new Person({ name: ‘PA’, age: 20, income: 20000, carOpt:{ brand: ‘BMW’, color: ‘pink’, output:’2.0T’ } }) var personB = new Person({ name: ‘PA’, age: 20, income: 10000, carOpt:{ brand: ‘Benz’, color: ‘black’, output:’1.8T’ } })
```