类class是在ES6才新增的,在这之前是通过构造函数和原型来模拟类的实现机制
ES5中创建对象的方式(复习)
<script>
// 1. 利用 new Object() 创建对象
var obj1 = new Object();
// 2. 利用 对象字面量创建对象
var obj2 = {};
// 3. 利用构造函数创建对象
function Star(uname, age) {
this.uname = uname;
this.age = age;
this.sing = function() {
console.log('我会唱歌');
}
}
var ldh = new Star('刘德华', 18);
var zxy = new Star('张学友', 19);
console.log(ldh);//Star?{uname: "刘德华", age: 18, sing: ?}
ldh.sing();
zxy.sing();
console.log(ldh.uname);//刘德华
</script>
ES6中创建对象的方式(类)
<script>
//1. 创建类class
class Star {
//new的时候自动调用constructor
constructor(uname, age) { //constructor可以传递参数
this.uname = uname;
this.age = age;
}
}
//2. 创建对象new
var ldh = new Star("刘德华", 18); //constructor可以返回实例对象
console.log(ldh); //Star {uname: "刘德华", age: 18}
</script>
原文:https://www.cnblogs.com/deer-cen/p/12382581.html