New syntax comes with ES6, class
and extends
emulate object-oriented behavior. However, this is just syntax sugar without any new magic, so it can be implemented merely by Javascript's nature.
class
ES6 syntax of class
class Name {
// class body
constructor(args) { constructor_body }
function method1(args1) { method_body }
}
var name = new Name(args);
name.method1();
It can be implemented by Object
function Name(args) {
constructor_body
}
Name.prototype.method1 = function(args1) {
method_body
};
var name = new Name(args);
name.method1();
extends
ES6 syntax of extends
class ParentClass {
parent_body
}
class ChildClass extends ParentClass {
child_body
}
var parent = new ParentClass(args);
var child = new ChildClass(args);
It can be implemented by literal assign:
function ParentClass(args) {
member1: ...
};
Parent.prototype.method1 = function() { ... };
function ChildClass (args) {
ParentClass.apply(this, args);
}
ChildClass.prototype = Object.crate(ParentClass.prototype);
ChildClass.prototype.constructor = ChildClass;
沒有留言:
張貼留言