簡體   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