JavaScript令人蒙圈的类创建
JavaScript类创建
函数的方法创建类
-
创建类的属性
var animal = function (name,age) {//创建一个动物类 this.name = name;//创建名字属性 this.age = age;//创建年龄属性 } -
创建类的方法
animal.prototype.showSelf = function () {//创建一个显示动物信息的公共方法 console.log("动物名称:"+this.name+" 动物年龄:"+this.age); }为什么使用prototype呢,这是一个该类的函数原型,包含了该类的成员集合,可以子类可以使用公共的showSelf方法,而不需要每一个类都建立了一个自己的showSelf方法
-
创建类的继承
var Dog = function(name,age,color){//继承animal类 animal.call(this,name,age);//动物类调用call方法直接强制把Dog的this强制改为自己的this this.color = color;//添加自己独有的color属性 } for(var value in animal.prototype){//通过遍历animal里面的共有方法,添加animal的prototype这些方法Dog的prototype对象里面 Dog.prototype[value] = animal.prototype[value]; }Dog继承animal的过程有点蒙圈,其实主要是通过在Dog里面让animal的this指向强制改变为Dog的this,实现了属性的继承,之后继续可以添加自己的类属性,之后再遍历父类的prototype对象,实现Dog的边遍历animal边复制到自己的prototype里面
-
创建类的多态
Dog.prototype.showColor = function () {//创建Dog的独有属性showColor实现多态 console.log("狗的颜色:"+this.color); } -
调用类
var dog = new Dog("狗",12,"红色"); dog.showSelf();//调用父类的方法 dog.showColor();//调用子类独有的方法
class方法创建类
-
创建类的属性和方法
class animal2{//用class声明animal2类 constructor(name,age) {//用constructor关键字创建name和age属性 this.name = name; this.age = age; } showSelf() {//直接创建方法toSelf console.log("动物名称:"+this.name+" 动物年龄:"+this.age); } } -
类的继承
class Cat extends animal { constructor(name,age,color) { super(name,age);//super直接能继承父类的属性 this.color = color;//创建自己独有的属性 } showColor(){//创建子类独有的方法 console.log("猫的颜色:"+this.color); } } -
调用类
var cat = new Cat("猫",13,"白色"); cat.showSelf(); cat.showColor();
函数构造父类,class构造子类混合继承
-
使用函数方法构造一个类
var animal = function (name,age) { this.name = name; this.age = age; } animal.prototype.showSelf = function () { console.log("动物名称:"+this.name+" 动物年龄:"+this.age); } -
使用class的extends关键字继承animal
class Cat extends animal { constructor(name,age,color) { super(name,age); this.color = color; } showColor(){ console.log("猫的颜色:"+this.color); } } var cat = new Cat("猫",13,"白色"); cat.showSelf(); cat.showColor();
总结
使用函数创建有点让人蒙圈,如果你学过java你应该会很容易理解class的创建过程,所以总体推荐使用class方法,书写的代码少,结构清晰易懂。
本文深入解析JavaScript中使用函数和class创建类的方法,包括属性、方法、继承和多态的实现,对比不同创建方式,推荐使用class语法提升代码可读性和效率。

1675

被折叠的 条评论
为什么被折叠?



