Is it possible to get the non-enumerable inherited property names of an object?

后端 未结 9 1845
温柔的废话
温柔的废话 2020-11-22 12:46

In JavaScript we have a few ways of getting the properties of an object, depending on what we want to get.

1) Object.keys(), which returns all own, enu

9条回答
  •  遥遥无期
    2020-11-22 13:36

    To get all inherited properties or methods for some instance you could use something like this

    var BaseType = function () {
        this.baseAttribute = "base attribute";
        this.baseMethod = function() {
            return "base method";
        };
    };
    
    var SomeType = function() {
        BaseType();
        this.someAttribute = "some attribute";
        this.someMethod = function (){
            return "some method";
        };
    };
    
    SomeType.prototype = new BaseType();
    SomeType.prototype.constructor = SomeType;
    
    var instance = new SomeType();
    
    Object.prototype.getInherited = function(){
        var props = []
        for (var name in this) {  
            if (!this.hasOwnProperty(name) && !(name == 'constructor' || name == 'getInherited')) {  
                props.push(name);
            }  
        }
        return props;
    };
    
    alert(instance.getInherited().join(","));
    

提交回复
热议问题