js对象检查是否定义了toString



我正在构建一个json格式化程序应用程序。并且我对CCD_ 1方法感到非常困惑。

假设我有一个对象。我将其解析为ulliDom树来进行说明。我添加了一个基于变量类型的标签。

function getText(val){
v = val.toString();
let p = document.createElement('span');
p.innerText = v;
return p;
}

它适用于常见类型,如stringnumber等,但是,当使用用户定义的对象时:

f = new TestClass();
console.log(getText(f));
{/* <span>[object Object]</span> */}

它产生了一个奇怪的结果。我读过相关的文章,比如OverwritingtoString函数,并了解它是如何工作的。

基本上,我理解javascript对象的toString方法与python的dunder__str__方法相同,例如,当类似于时

`${f}`

则调用CCD_ 8。然后我试着看看它是在哪里定义的,它继承自什么基类,但我一无所获。super is not allowed in this context


对于用户定义的对象,我如何确定服装toString0是否在实例上定义?

类似于:

class TestClass1{

}
class TestClass2{
toString(){
}
}
console.log(new TestClass1().toString === undefined)
// should return true
console.log(new TestClass2().toString === undefined)
// should return false

您可以在他们的原型中检查toString()是否与Object的相同:

TestClass.prototype.toString === Object.prototype.toString

或者,通过一个实例:

// preferred method:
Object.getPrototypeOf(testClassInstance).toString === Object.prototype.toString
// alternative accessing __proto__ directly:
testClassInstance.__proto__.toString === Object.prototype.toString

演示:

class TestClass {
toString() { return 'I am TestClass'; }
}
const tc = new TestClass();
class ClassWithoutToString { }
const cwts = new ClassWithoutToString();
console.log(
TestClass.prototype.toString === Object.prototype.toString,
ClassWithoutToString.prototype.toString === Object.prototype.toString
);
console.log(
Object.getPrototypeOf(tc).toString === Object.prototype.toString,
Object.getPrototypeOf(cwts).toString === Object.prototype.toString
);

最新更新