很全面的JavaScript常用功能汇总集合(3)

class Person { constructor( first, last) { this.firstName = first; this.lastName = last; } toString() { return this.firstName + " " + this.lastName; } static checkLastName( ln) { if (typeof(ln)!=="string" || ln.trim()==="") { console.log("Error: " + "invalid last name!"); } } }

Step 1.b 类层次的属性定义:

Person.instances = {};
在第二步中,会定义一个带有其他属性和方法的子类,也有可能重写父类的相关方法:

class Student extends Person { constructor( first, last, studNo) { super.constructor( first, last); this.studNo = studNo; } // method overrides superclass method toString() { return super.toString() + "(" + this.studNo +")"; } }

ES5中,可以定义继承基于构造器类的子类。如下:

Step1.a 首先定义构造函数,能够隐式的定义类的属性并赋值;

function Person( first, last) { this.firstName = first; this.lastName = last; }

注意,上述代码中的this 指的是新生成的对象,当构造函数被调用时,该对象就已经生成了。

Step1.b 定义实例层的方法:

Person.prototype.toString = function () { return this.firstName + " " + this.lastName; }

Step 1.c 定义静态方法:

Person.checkLastName = function (ln) { if (typeof(ln)!=="string" || ln.trim()==="") { console.log("Error: invalid last name!"); } }

Step 1.d 定义类层次的静态属性

Person.instances = {};

Step 2.a 定义子类:
1: function Student( first, last, studNo) {
2: // invoke superclass constructor
3: Person.call( this, first, last);
4: // define and assign additional properties
5: this.studNo = studNo;
6: }
通过调用超类的构造函数Person.call( this, ...),来创建新对象。其中This指的是Student,Property Slots 在超类的构造函数中已经创建((firstName 和lastName) 以及其他子类相关的属性。在这种情况下可使用Property Inheritance 机制保证所有的属性已经被定义且被创建。

Step2b,通过构造函数的prototype 属性安装method inheritance 。如下,分配了一个新对象创建子类型构造函数的Prototype 属性,并做出适当的调整:

// Student inherits from Person Student.prototype = Object.create( Person.prototype); // adjust the subtype's constructor property Student.prototype.constructor = Student;

Step2c, 重新定义子类方法重写超类方法:

Student.prototype.toString = function () { return Person.prototype.toString.call( this) + "(" + this.studNo + ")"; };

基于构造器类的实例化是通过应用new 操作符来创建的,并提供合适的构造参数:

var pers1 = new Person("Tom","Smith");

方法toString 通过pers1. 来调用:

alert("The full name of the person are: " + pers1.toString());

在JS中,prototype 是具有method slots 的对象,可以通过JS方法或属性槽继承的。

七、基于Factory 的类
在该方法中定义了JS 对象Person,含有特殊的Create 方法来调用预定义的Object.Create方法,创建Person类型的对象;

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgwgfx.html