This is the 27th day since I participated in the August Gwen Challenge.
JavaScript advanced
JavaScript Advanced (2)
JavaScript advanced (three) modular
JavaScript advanced (4) anti-shake
JavaScript advanced (five) throttling
JavaScript is confusing to developers who have worked with class-based languages such as Java or C++ – JavaScript is dynamic and does not provide a class implementation of its own. Even the class keyword was introduced in ES2015/ES6, but that was just syntactic sugar and JavaScript was still prototype-based.
inheritance
ES5
- First let’s look at how inheritance is implemented in ES 5
function son() {
son.prototype.getName = function() {
return 'son'
}
function father() {}
let name = new father()
father.prototype = Object.create(son.prototypeConstructor: {constructor: {name: 'father', sex: 'male', age: '66'}})Copy the code
- In the code above, we give the son method to father in the form of a prototype chain
ES6
- ES, we can provide Class keywords and
extends
To implement inheritance
class father {
getName() {
return 'father'
}
}
class son extends father {
getName() {
return 'son'
}
}
let bigSon = new son()
bigSon.getName(a)Copy the code
The above code implements inheritance using ES6 syntax and reconstructs the getName method.
- One thing to note, though, is that while ES6 is common, there are some older projects that do not inherit ES6 syntax, and we need a coding tool to convert it to ES5 syntax. This is Babel
So how did he do that? We can look at the translated code in any translation tool.
var father = function () {
function father() {
_classCallCheck(this, father);
}
_createClass(father, [{
key: 'getName',
value: function getName() {
return'father'; }}]);returnfather; } ();var son = function (_father) {
_inherits(son, _father);
function son() {
_classCallCheck(this, son);
return _possibleConstructorReturn(this, (son.__proto__ || Object.getPrototypeOf(son)).apply(this, arguments));
}
_createClass(son, [{
key: 'getName',
value: function getName() {
return'son'; }}]);return son;
}(father);
var bigSon = new son();
bigSon.getName(a);Copy the code
- As you can see from the above code, this is the ES5 syntax, but it is important to note that it is used in ES5
apply
This method.
END~~~