栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何从javascript中的类继承?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从javascript中的类继承?

我已经更改了现在的操作方式,我尝试避免使用构造函数和它们的

prototype
属性,但是我从2010年起的旧答案仍然是最底层的。我现在更喜欢
Object.create()
Object.create
适用于所有现代浏览器。

我应该注意,这

Object.create
通常比使用函数构造函数慢得多
new

//The prototype is just an object when you use `Object.create()`var base = {};//This is how you create an instance:var baseInstance = Object.create(base);//If you want to inherit from "base":var subInstance = Object.create(Object.create(base));//Detect if subInstance is an instance of base:console.log(base.isPrototypeOf(subInstance)); //True

使用Object.create的最大好处之一就是能够传递defineProperties参数,该参数使您可以有效控制如何访问和枚举类的属性,并且我还使用函数来创建实例,这些函数可以用作构造函数,因为您可以在最后进行初始化,而不仅仅是返回实例。

var base = {};function createbase() {  return Object.create(base, {    doSomething: {       value: function () {         console.log("Doing something");       },    },  });}var Sub = createbase();function createSub() {  return Object.create(Sub, {    doSomethingElse: {      value: function () {        console.log("Doing something else");      },    },  }); }var subInstance = createSub();subInstance.doSomething(); //Logs "Doing something"subInstance.doSomethingElse(); //Logs "Doing something else"console.log(base.isPrototypeOf(subInstance)); //Logs "true"console.log(Sub.isPrototypeOf(subInstance)); //Logs "true

这是我2010年的原始答案:

function base ( ) {  this.color = "blue";}function Sub ( ) {}Sub.prototype = new base( );Sub.prototype.showColor = function ( ) { console.log( this.color );}var instance = new Sub ( );instance.showColor( ); //"blue"


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614727.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号