JavaScript 什么是.extend和.prototype的用途
Extend: JavaScript/jQuery extend 方法将源对象的所有属性复制到目标对象中。 extend 方法的主要用途是在类声明中创建一个子类(派生类),该子类是另一个父类(超类)的子类。它可以用于子类化内置对象和用户定义的(自定义)类。
语法:
class child_class extends parent_class {
// class definition goes here
}
示例:
// 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语言中的原型属性是一种独特的特性。原型属性作为对象的成员存在,它的主要用途是允许向对象构造函数添加新的属性(成员或函数)。它还用于从一个对象继承功能到另一个对象上。之所以需要原型,是因为JavaScript不允许向现有的对象构造函数添加新的属性。
语法:
ClassName.prototype.property = value;
// For class members:
ClassName.prototype.member_name = member_value;
// For class methods:
ClassName.prototype.function_name = function() {
// function definition
};
示例:
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;
};