program story

디버깅을위한 의미있는 출력을 제공하기 위해 JavaScript의 toString () 함수를 재정의 할 수 있습니까?

inputbox 2020. 8. 12. 08:14
반응형

디버깅을위한 의미있는 출력을 제공하기 위해 JavaScript의 toString () 함수를 재정의 할 수 있습니까?


console.log()JavaScript 프로그램에서 객체 일 출력 만 [object Object]보는데, 이는 그것이 어떤 객체 (또는 어떤 유형의 객체)인지 알아내는 데별로 도움이되지 않습니다.

C #에서는 ToString()개체의 디버거 표현을 사용자 지정할 수 있도록 재정의 하는 데 익숙 합니다. JavaScript에서 비슷한 작업이 있습니까?


toStringJavascript에서도 재정의 할 수 있습니다 . 예를보십시오 :

function Foo() 
{
}

// toString override added to prototype of Foo class
Foo.prototype.toString = function()
{
    return "[object Foo]";
}

var f = new Foo();
alert(f);  // popup displays [object Foo]

JavaScript에서 객체 유형 이름을 결정하는 방법에 대한 토론을 참조하십시오 .


먼저 toString개체 또는 프로토 타입을 재정의 합니다.

var Foo = function(){};
Foo.prototype.toString = function(){return 'Pity the Foo';};

var foo = new Foo();

그런 다음 문자열로 변환하여 객체의 문자열 표현을 확인합니다.

//using JS implicit type conversion
console.log('' + foo);

추가 입력이 마음에 들지 않으면 인수의 문자열 표현을 콘솔에 기록하는 함수를 만들 수 있습니다.

var puts = function(){
    var strings = Array.prototype.map.call(arguments, function(obj){
        return '' + obj;
    });
    console.log.apply(console, strings);
};

용법:

puts(foo)  //logs 'Pity the Foo'

puts(foo, [1,2,3], {a: 2}) //logs 'Pity the Foo 1,2,3 [object Object]'

최신 정보

E2015는이 항목에 대해 훨씬 더 좋은 구문을 제공하지만 Babel 과 같은 변환기를 사용해야합니다 .

// override `toString`
class Foo {
  toString(){
    return 'Pity the Foo';
  }
}

const foo = new Foo();

// utility function for printing objects using their `toString` methods
const puts = (...any) => console.log(...any.map(String));

puts(foo); // logs 'Pity the Foo'

브라우저 JS에서 디버깅 가능한 출력을 얻는 쉬운 방법은 객체를 JSON으로 직렬화하는 것입니다. 그래서 당신은 다음과 같이 전화를 걸 수 있습니다.

console.log ("Blah: " + JSON.stringify(object));

예를 들어, alert("Blah! " + JSON.stringify({key: "value"}));텍스트가있는 경고를 생성합니다.Blah! {"key":"value"}


Node를 사용하는 경우 고려해 볼 가치가 있습니다 util.inspect.

var util = require('util')

const Point = {
  x: 1,
  y: 2,
  [util.inspect.custom]: function(depth) { return `{ #Point ${this.x},${this.y} }` }

}

console.log( Point );

이렇게하면

{ #Point 1,2 }

검사하지 않은 버전이 인쇄되는 동안 :

{ x: 1, y: 2 }

toString()메서드를 재정의하십시오 .

간단한 예 :

var x = {foo: 1, bar: true, baz: 'quux'};
x.toString(); // returns "[object Object]"
x.toString = function () {
    var s = [];
    for (var k in this) {
        if (this.hasOwnProperty(k)) s.push(k + ':' + this[k]);
    }
    return '{' + s.join() + '}';
};
x.toString(); // returns something more useful

새 유형을 정의 할 때 더 좋습니다.

function X()
{
    this.foo = 1;
    this.bar = true;
    this.baz = 'quux';
}

X.prototype.toString = /* same function as before */

new X().toString(); // returns "{foo:1,bar:true,baz:quux}"

객체가 직접 정의 된 경우 항상 toString 재정의를 추가 할 수 있습니다.

//Defined car Object
var car = {
  type: "Fiat",
  model: 500,
  color: "white",
  //.toString() Override
  toString: function() {
    return this.type;
  }
};

//Various ways to test .toString() Override
console.log(car.toString());
console.log(car);
alert(car.toString());
alert(car);

//Defined carPlus Object
var carPlus = {
  type: "Fiat",
  model: 500,
  color: "white",
  //.toString() Override
  toString: function() {
    return 'type: ' + this.type + ', model: ' + this.model + ', color:  ' + this.color;
  }
};

//Various ways to test .toString() Override
console.log(carPlus.toString());
console.log(carPlus);
alert(carPlus.toString());
alert(carPlus);


템플릿 리터럴 :

class Foo {
  toString() {
     return 'I am foo';
  }
}

const foo = new Foo();
console.log(`${foo}`); // 'I am foo'

The Chrome console log allows you to inspect the object.


-This operation takes lot of time to complete, and it's use is discouraged according to mozilla docs: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/proto

-Apparently, modern browsers deprecated .prototype and ECMA6 specifies using proper__proto__ instead.

So for example, if you are defining you own object geoposition you should call __proto__ property instead of .prototype:

var  geoposition = {

        lat: window.pos.lat,
        lng: window.pos.lng
    };

geoposition.__proto__.toString = function(){ return "lat: "+this.lat+", lng: "+this.lng }
console.log("Searching nearby donations to: "+geoposition.toString());

Here's an example how to stringify a Map object:

  Map.prototype.toString = function() {

    let result = {};

    this.forEach((key, value) => { result[key] = value;});

    return JSON.stringify(result);
  };

You can give any custom objects their own toString methods, or write a general one that you can call on the object you are looking at-

Function.prototype.named= function(ns){
    var Rx=  /function\s+([^(\s]+)\s*\(/, tem= this.toString().match(Rx) || "";
    if(tem) return tem[1];
    return 'unnamed constructor'
}

function whatsit(what){
    if(what===undefined)return 'undefined';
    if(what=== null) return 'null object';
    if(what== window) return 'Window object';
    if(what.nodeName){
        return 'html '+what.nodeName;
    }
    try{
        if(typeof what== 'object'){
            return what.constructor.named();
        }
    }
    catch(er){
        return 'Error reading Object constructor';
    }
    var w=typeof what;
    return w.charAt(0).toUpperCase()+w.substring(1);
}

Rather than overriding toString(), if you include the Prototype JavaScript Library, you can use Object.inspect() to get a much more useful representation.

Most popular frameworks include something similar.


You can extend or override in JS

String.prototype.toString = function() {
    return this + "..."
}
document.write("Sergio".toString());


A simple format Date function using Javascript prototype, it can be used for your purpose

https://gist.github.com/cstipkovic/3983879 :

Date.prototype.formatDate = function (format) {
    var date = this,
        day = date.getDate(),
        month = date.getMonth() + 1,
        year = date.getFullYear(),
        hours = date.getHours(),
        minutes = date.getMinutes(),
        seconds = date.getSeconds();

    if (!format) {
        format = "MM/dd/yyyy";
    }

    format = format.replace("MM", month.toString().replace(/^(\d)$/, '0$1'));

    if (format.indexOf("yyyy") > -1) {
        format = format.replace("yyyy", year.toString());
    } else if (format.indexOf("yy") > -1) {
        format = format.replace("yy", year.toString().substr(2, 2));
    }

    format = format.replace("dd", day.toString().replace(/^(\d)$/, '0$1'));

    if (format.indexOf("t") > -1) {
        if (hours > 11) {
            format = format.replace("t", "pm");
        } else {
            format = format.replace("t", "am");
        }
    }

    if (format.indexOf("HH") > -1) {
        format = format.replace("HH", hours.toString().replace(/^(\d)$/, '0$1'));
    }

    if (format.indexOf("hh") > -1) {
        if (hours > 12) {
            hours -= 12;
        }

        if (hours === 0) {
            hours = 12;
        }
        format = format.replace("hh", hours.toString().replace(/^(\d)$/, '0$1'));
    }

    if (format.indexOf("mm") > -1) {
        format = format.replace("mm", minutes.toString().replace(/^(\d)$/, '0$1'));
    }

    if (format.indexOf("ss") > -1) {
        format = format.replace("ss", seconds.toString().replace(/^(\d)$/, '0$1'));
    }

    return format;
};

참고URL : https://stackoverflow.com/questions/6307514/is-it-possible-to-override-javascripts-tostring-function-to-provide-meaningfu

반응형