.extend 和 .prototype 是做什么用的?
延长:
JavaScript / jQuery扩展方法将所有属性从源对象复制到目标对象。 extend方法的主要用途是在类声明中,目的是创建一个类(子类),该类是另一个父类(超类)的子类。它可用于子类化内置对象以及用户定义(自定义)类。
句法:
class child_class extends parent_class {
// class definition goes here
}
例子:
Javascript
// Parent Class
class Animal {
constructor(name) {
this.name = name;
}
}
// Child Class
class Dog extends Animal {
constructor(name) {
// the super keyword to used to call
// the constructor of the parent class
super(name);
this.name = name;
}
}
Javascript
class Employee {
let firstName;
let lastName;
// constructor
Employee (first, last) {
this.firstName = first;
this.lastName = last;
}
}
// add class data member
Employee.prototype.email = "example@gmail.com";
// add class member function
Employee.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};
原型:
原型属性是 JavaScript 语言的一个独特特性。原型属性充当对象的成员。它的主要用途是允许向对象构造函数添加新属性(成员或函数)。它还用于从一个到另一个继承特性。由于 JavaScript 不允许向现有对象构造函数添加新属性,因此需要进行原型设计。
句法:
ClassName.prototype.property = value;
// For class members:
ClassName.prototype.member_name = member_value;
// For class methods:
ClassName.prototype.function_name = function() {
// function definition
};
例子:
Javascript
class Employee {
let firstName;
let lastName;
// constructor
Employee (first, last) {
this.firstName = first;
this.lastName = last;
}
}
// add class data member
Employee.prototype.email = "example@gmail.com";
// add class member function
Employee.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};