欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > ES6 Class 转 ES5 实现

ES6 Class 转 ES5 实现

2025/3/14 17:49:03 来源:https://blog.csdn.net/weixin_45718102/article/details/145967783  浏览:    关键词:ES6 Class 转 ES5 实现

ES6 示例代码

class Animal {constructor(name) {this.name = name;}eat() {console.log(`${this.name} is eating`);}static sleep() {console.log("Sleeping");}
}class Dog extends Animal { // 原型链继承 + 静态方法继承constructor(name, breed) {super(name);this.breed = breed;}bark() {super.eat(); // 调用父类构造函数console.log("Woof!");}
}

 

ES5 代码实现

// 父类Animal
function Animal(name) {this.name = name;
}// 实例方法
Animal.prototype.eat = function() {console.log(this.name + " is eating");
};// 静态方法
Animal.sleep = function() {console.log("Sleeping");
};// 子类Dog
function Dog(name, breed) {Animal.call(this, name);this.breed = breed;
}// 继承原型链
Object.setPrototypeOf(Dog, Animal); // 静态方法继承
Dog.prototype = Object.create(Animal.prototype, {constructor: { value: Dog, enumerable: false, // 方法自动绑定}
});// 子类方法
Dog.prototype.bark = function() {Animal.prototype.eat.call(this);console.log("Woof!");
};

转换点

ES6ES5
class构造函数 + 原型方法
extendsObject.create() + Parent.call()
superParent.call(this, args)
super.method()Parent.prototype.method.call(this)
静态方法直接挂载到构造函数上
原型方法默认是不可枚举的‌enumerable: false

 

附加点:

虽然class的原型方法默认不可枚举,但可以通过Object.defineProperty()方法将enumerable属性设置为true,这样就可以遍历到这些方法了:

Object.defineProperty(obj, 'testMethod', {enumerable: true});
console.log(Object.keys(obj)); // ['testMethod']

 

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词