JavaScript based learning -class
class
es6 added a class, you can make better use of classes and inheritance design patterns, containing super syntactic sugar can be achieved override inherited, the method of the class.
The method does not need to write function key
can not declare a property, you can only declare methods
can be inherited internal objects, such as Array
class A {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`hello ${this.name}`);
}
saySeeYou() {
console.log('see you');
}
}
class B extends A {
constructor(name, age) {
super(name);
this.age = age;
}
sayHello() {
super.sayHello();
console.log(`age ${this.age}`);
}
}
var a = new A('jsong');
a.sayHello(); // hello jsong
var b = new B('jsong', '11');
b.sayHello(); // hello jsong
// age 11
b.saySeeYou(); // see you
es5 wording
Surface es6 writing classes and java is very similar, but the relationship between the classes and subclasses of objects and relationships are still prototypes commissioned, no copy of the class. But in the internal implementation of a class of tedious writing js, let us more easily use the class.
es5 wording
function A(name) {
this.name = name;
}
A.prototype.sayHello = function() {
console.log(`hello ${this.name}`);
};
A.prototype.saySeeYou = function() {
console.log('see you');
};
function B(name, age) {
A.call(this, name);
this.age = age;
}
B.prototype = Object.create(A.prototype);
B.prototype.sayHello = function() {
A.prototype.sayHello.call(this);
console.log(`age ${this.age}`);
};
var a = new A('jsong');
a.sayHello(); // hello jsong
var b = new B('jsong', '11');
b.sayHello(); // hello jsong
// age 11
b.saySeeYou(); // see you
Prototype class or relationship
class does not implement replication relationship classes and objects, it is still by [[Prototype]] commission, so there will be a reference to an object is an object relationship with
the method to modify the prototype class C, whether it is the object of c1 or c2 new object will change their approach, because the prototype c1 and c2 are jointly commissioned class C's.
class C {
sayHello() {
console.log('hello world');
}
}
var c1 = new C();
c1.sayHello(); // hello world
C.prototype.sayHello = function() {
console.log('see you world');
};
var c2 = new C();
c2.sayHello(); // see you world
c1.sayHello(); // see you world
How to declare property
not permitted to declare class attributes, but we can add properties need to be declared in the class of the object protype
class C {
constructor() {
C.prototype.count++;
console.log(`hello ${this.count}`);
}
}
C.prototype.count = 0;
var c1 = new C(); // hello 1
console.log(c1.count); // 1
var c2 = new C(); // hello 2
console.log(c1.count); // 2
console.log(c2.count); // 2