Let's review the methods implemented with functions Student
:
function Student(name) { this.name = name;}Student.prototype.hello = function () { alert(‘Hello, ‘ + this.name + ‘!‘);}
If you write with a new class
keyword Student
, you can write it like this:
class student {constructor (name) {this.name = name; } hello () {alert ( ' Hello, ' + this.name + '! '); }}
compare to find out, The definition of class
contains the constructor constructor
and the function defined on the prototype object Hello ()
Another great benefit of defining objects with class
is that inheritance is more convenient. , think of the amount of code we need to write from Student
to derive a primarystudent
. Now, the intermediate object inherited by the prototype, the constructor of the prototype object, and so on, need not be considered, directly through the extends
to implement:
Class Primerestudent extends Student (name,grade) { Constructor (Name,grade) { super (name); This.grade=grade; } Saygrade () { return (' My grade is: ' + This.grade);} }
Explanation: To want to inherit, must have extends,constructor, super (xxxx), we here, constructor constructor,name is we inherit, so want super (name)/* like Python */, Grade is the new parameter, so to This.grade=grade,
Asygrade is our own function, so declare it.
Js-class inheritance