继承如何在ES5-Javascript中工作? [英] How does inheritance work in ES5-Javascript?

查看:111
本文介绍了继承如何在ES5-Javascript中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码,

  var customer = {
name:Tom Smith,

发言:function(){
返回我的名字是+这个['name'];
},

地址:{
街道:'123 Main St',
city:匹兹堡,
州:PA
}
};

以下是我对客户对象的可视化,



< hr>

,但是也将继承,它不仅是内置的。


Object的属性(内置函数)是否也是继承的目的是什么?


没有。它们是静态函数,应该以对象作为参数调用,而不是对象方法。


客户对象的语法是什么继承对象属性?


对象是一个函数,通常你不会t 希望继承它。如果你真的想要,你可以使用 Object.create(Object)



此外,ES6增加了一种新的方式要做到这一点,因为 class es也从其父级继承静态方法:

  class MyObject extends Object {
static myCreate(x){
return this.create(x);
}
}


For the below code,

           var customer={
                name: "Tom Smith",

                speak: function(){
                    return "My name is " + this['name'];
                },

                address: {
                    street: '123 Main St',
                    city: "Pittsburgh",
                    state: "PA"
                }
            };

Below is my visualisation of customer object,


My question:

Does customer object inherit properties(built-ins) of Object.prototype only?

Are the properties(built-ins) of Object function type object are also for the purpose of inheritance?

If yes, What is the syntax for customer object to inherit Object properties?

解决方案

Below is my visualisation of customer object

It would be better if you used the term [[prototype]] instead of __proto__ - as you can see, .__proto__ is just a getter/setter inherited from Object.prototype.

Does customer object inherit properties(built-ins) of Object.prototype only?

Yes. Though you could add your own properties to Object.prototype, they would be inherited as well, it's not only the built-in ones.

Are the properties(built-ins) of Object are also for the purpose of inheritance?

No. They're static functions that are supposed to be called with objects as their arguments, not object methods.

What is the syntax for customer object to inherit Object properties?

Object is a function and usually you don't want to inherit from it. If you really wanted, you could use Object.create(Object).

Also, ES6 adds a new way to do that, as classes inherit static methods from their parent as well:

class MyObject extends Object {
    static myCreate(x) {
        return this.create(x);
    }
}

这篇关于继承如何在ES5-Javascript中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆