对象的创建方法:
- 字面量
- new Object
- 构造函数
- 类的实例化
<script>
// 1字面量方式
var xx = {
name: '蜡笔小新',
age: 3
}
console.log(xx);
// 2 new Object()方式
var xx = new Object();
xx.name = '蜡笔小新';
xx.age = 3;
xx.showSkill = function() {
console.log('扮鬼脸');
};
console.log(xx);
// 3构造函数方式
function People(name, age) {
this.name = name;
this.age = age;
}
var xx = new People('蜡笔小新', 3) //实例化对象
console.log(xx);
</script>
输出:
<script>
//4 类的实例化
class People {
//类的共有属性放到 constructor 里面
constructor(name, age) {
this.name = name;
this.age = age;
}
//注意:方法与方法之间不需要添加逗号
sing(song) {
console.log(this.name + '唱' + song);
}
}
var xx = new People('蜡笔小新', 3);
console.log(xx);
xx.sing('动感超人');
</script>