ES5和ES6中实现对象和继承的方法对比
ES5中创建一个对象(或者叫做类),通常使用构造函数定义实例属性,原型模式用于定义方法和共享属性。对象实例可以访问原型中的值,但不能修改原型中的值。
function Person(name, age) {
this.name = name;
this.age = age;
this.friends = ['one', 'two']
}
Person.prototype = {
constructor: Person,
sayName: function() {
alert(this.name);
}
}
var p1 = new Person('ren',18);
var p2 = new Person('zhiwei', 18);
console.log(p1.friends)
console.log(p2.friends)
alert(p1.friends == p2.friends) // false new调用构造函数创建了一个新对象,所以friends数组不同
ES6中引入Class概念创建一个类。
class Person {
// 相当于 function Person(name, age){......}
constructor(name, age) {
this.name = name;
this.age = age;
this.friends = ['one', 'two'];
}
// 相当于Person.prototype = {...}
sayName() {
alert(this.name);
}
}
let p1 = new Person('nihao', 18);
p1.sayName();
console.log(p1.friends);
ES5中实现继承,通过在继承的函数中调用call()或者apply()方法实现继承
function SuperType(name) {
this.name = name;
this.color = ["red", "blue"];
}
SuperType.prototype.sayName = function() {
alert(this.name);
}
function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
var s1 = new SubType('ren');
s1.sayName();
console.log(s1.color);
ES6中在constructor()中调用super()可继承基类。
class SuperType {
constructor(name) {
this.name = name;
this.color = ["red", "blue"];
}
sayName() {
alert(this.name);
}
}
class SubType extends SuperType {
constructor(name, age) {
// 相当于SuperType.call(this, name);
super(name);
this.age = age;
}
}
var s1 = new SubType('ren', 19);
console.log(s1);