How does inheritance work in ES5-Javascript?

牧云@^-^@ 提交于 2019-12-08 08:37:26

问题


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?


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/34050143/how-does-inheritance-work-in-es5-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!