js中的类和类的继承

it2026-04-02  6

es5中没有类的概念,通过构造函数和原型对象间接实现类的效果。

通过构造函数实现类 function Person(name) { this.name = name; this.say = function() { console.log(`我是${ this.name }`); }; } let zs = new Person('zs'); zs.say(); // 我是zs let ls = new Person('ls'); ls.say(); // 我是ls

优点:各个对象各自持有一份数据,互不干扰 缺点:内部有函数时,会造成内存的浪费

通过原型对象实现类 function Person() {} Person.prototype.name = ""; Person.prototype.say = function() { console.log(`我是${ this.name }`); }; let zs = new Person('zs'); zs.say(); // 我是zs let ls = new Person('ls'); ls.say(); // 我是ls

优点:所有对象共用一份数据,没有内存上的浪费 缺点:数据共用,一个对象对数据的修改会导致其他所有对象中的数据也会变化

通过构造函数和原型对象实现类 function Person(name) { this.name = name; } Person.prototype.say = function() { console.log(`我是${ this.name }`); }; let zs = new Person('zs'); zs.say(); // 我是zs let ls = new Person('ls'); ls.say(); // 我是ls

把属性定义在构造函数中,把方法挂载在构造函数的原型对象上,结合了构造函数和原型对象两者的优点,避免了两者的缺点。

动态公有属性:所有对象各自持有,可以通过对象直接点来访问赋值 动态私有属性:所有对象各自持有,不能通过对象直接点来访问赋值

静态私有属性:把构造函数放在一个IIFE表达式中作为返回值,并闭包IIFE中的局部变量,这个局部变量就是一个静态属性,所有对象共同持有 静态公有属性:在构造函数的原型对象上挂载的属性

var Person = (function() { var b = "aaa"; // 静态私有属性 return function(name, age, height) { var a = 100; // 动态私有属性 this.getA = function() { return a; }; this.setA = function(val) { a = val; }; this.getB = function() { return b; }; this.setB = function(val) { b = val; }; this.name = name; // 动态公有属性 this.age = age; this.height = height; }; })(); Person.prototype.say = function() {}; // 静态公有属性

对于私有属性,外部不能直接进行访问和赋值,只能通过公有的函数间接访问和赋值,公有的函数通过闭包能够实现对私有属性的访问和赋值。

es6中的类

class Person { static a = 100; static fun() { console.log('这是一个静态方法'); } constructor(name) { this.name = name; } say() { console.log('我是' + this.name); } }

继承

es5实现继承

实际上是通过构造函数加原型对象实现的

// 父类:Person function Person(name) { this.name = name; } Person.prototype.say = function() { console.log(this.name); }; // 子类:Doctor function Doctor(name, major) { Person.call(this, name); this.major = major; } Doctor.prototype = new Person(); Doctor.prototype.constructor = Doctor; Doctor.prototype.kanbing = function() { console.log(this.name + '正在看病'); }; var ml = new Doctor('ml', '儿科'); ml.say(); // ml ml.kanbing(); // ml正在看病

子类Doctor通过Person.call(this, name)继承了父类Person的name公有属性,major是自身特有的属性; Doctor.prototype = new Person(); 使Doctor子类的原型对象指向了通过Person构造出来的新对象,此时Doctor的所有实例都具有了say方法;但是副作用是Doctor实例找不到自己原来的构造函数了,所以通过Doctor.prototype.constructor = Doctor使Doctor的实例能够找到自己的构造函数;然后在Doctor的原型对象上动态开辟静态公有属性。

es6实现继承

class Person { construcor(name) { this.name = name; } say() { console.log(this.name); } } class Doctor extends Person { constructor(name, major) { super(name); this.major = major; } kanbing() { console.log(this.name + '正在看病'); } } let doctor = new Doctor('ml', '儿科'); doctor.say(); // ml doctor.kanbing(); // ml正在看病
最新回复(0)