繁体   English   中英

如何使用点表示法在JavaScript中向数组和对象原型添加console.log方法?

[英]How do you add a console.log method on to arrays and objects prototypes in JavaScript using the dot notation?

如何使用点表示法在javascript中的数组和对象上创建日志方法?

 function log(...k){ console.log.apply(console, k) } log('hello') //=> prints hello //I want to do this for arrays and objects using the dot notation ['hello','world'].log() //=> prints ['hello', 'world'] {'hello':'world'}.log() //=> prints {'hello', 'world'} 

您可以将此方法添加到数组原型中,如下所示:

 var array = ['hello','world']; Array.prototype.log = function(){ (this).forEach(function(item){ console.log(item); }); }; array.log(); 

关于一个对象,你可以通过将函数添加到对象原型来做同样的事情:

 var obj = { 'hello' : 'world' }; Object.prototype.log = function(){ Object.keys(this).forEach(function(key){ console.log(key); console.log((obj[key])); }); }; obj.log(); 

就像你说的那样,修改原型。

 function log(...k) { console.log.apply(console, k); } Array.prototype.log = function() { log.apply(null, ['['].concat(this).concat([']'])); }; Object.prototype.log = function() { let vals = ['{']; for (var key in this) { if (this.hasOwnProperty(key)) { vals.push(key, this[key]); } } vals.push('}'); log.apply(null, vals); }; ['hello', 'world'].log(); ({ hello: 'world' }).log(); 

请不要随意乱动原生原型。 这可能(并且很可能会)导致您大量头痛。 而是使用Object.defineProperty()并正确定义新方法。

 Array.prototype.log = Array.prototype.log; if(Array.prototype.log === undefined) { Object.defineProperty(Array.prototype, 'log', { enumerable: false, value: function () { (this).forEach(function(item){ console.log(item); }); } }); } Object.prototype.log = Object.prototype.log; if(Object.prototype.log === undefined) { Object.defineProperty(Object.prototype, 'log', { enumerable: false, value: function (el, offset) { var self = this; Object.keys(this).forEach(function(key){ console.log(key + ':', (self[key])); }); } }); } var testArr = [1, 2, 'foo', 'bar']; var testObj = {one: 1, two: 2, foo: 'bar'}; testArr.log(); testObj.log(); 

在javascript中有什么叫做prototypes Prototypes也是objects ,您可以将成员( methods properties )分配给。 在您的情况下,如果要创建适用于特定原始值的函数,则必须将该特定函数作为方法添加到原始值的构造函数的原型中。 例如,在您的情况下,您必须在ArrayObject构造函数的原型上创建一个函数作为方法

Array.prototype.log = function() {    
    for ( let __elements of this ) {
        // uh
        // incase it's an array of array
        if ( Array.isArray(__elements) ) {
            __elements.log();
        } else {
            console.log(__elements);
        }
    } 
};



Object.prototype.log = function() {
    for ( let _prop in this ) {
        // typeof [] always returns an object
        if ( this.hasOwnProperty(_prop) ) {
            if ( typeof this[_prop] === 'object' && ! 
                Array.isArray(this[_prop]) ) {
                this[_prop].log();
            } else {
                console.log(this[_prop]);
            }
        }
    }
};


[1,2,3,4].log();

[[1,2,[3,4]],3,[2]].log();

let obj = {
    name:"victory",
    surname: "osikwemhe",
    life: {
        occupation: ["accontant","programmer"],
        hobbies: "danching gnamgnam style",
        hates: "sharing my wifi",
        tvshows: {
            "cw": ["the flash"],
            "hbo": ["silicon valley"],
            "history": ["vikings"]
        }        
    } 
};


obj.log();

如果你正在调整this一点, this指向我们使用log方法的原始值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM