簡體   English   中英

例如,如何像字符串一樣創建 object? 具有許多屬性和默認 console.log/evaluation 值的 object

[英]How can I create a object like a string, for example? A object with many properties, and a default console.log/evaluation value

我想創建一個具有許多屬性的 object,但是,當我只是 console.log 我的 object 或將其插入評估時,它確實有一個默認值來評估或記錄,一個原始值,例如“測試”。

我嘗試使用 getter 和 setter 但沒有成功。

const obj = { a: 'test1', b: 'test2' } // this is my object

console.log(obj.a); // this should return 'test1'

console.log(obj); // this should return a value of my choice, like 'testobj' or a number

'testobj' === obj; // should be true, since I want my obj to have a default value of 'testobj' in evaluations
// just like a primitive type, like strings or numbers. They have many functions and a default value

當 object 被視為字符串時,JavaScript 運行時將查看它是否具有toString()方法,並將返回該方法指示的任何內容。 如果沒有toString() ,那么通常你會看到[object Object] 此外,要生成基礎原始值,請給 object 一個valueOf值。

此外,在制作將以這種方式使用的對象時,請使用構造函數,而不是 object 文字。

 const objA = function(){ this.a= 'test1'; this.b= 'test2' } let instA = new objA(); console.log(instA.toString()); const objB = function() { this.a= 5; this.b= 'test2'; this.toString= function(){ return this.a; }; this.valueOf = function() { return this.toString(); }; } let instB = new objB(); console.log(instB.toString()); console.log(instB + 2); // Get the primitive and work with that

一年后,我再次遇到這個問題並找到了解決方案。 我的目標是使用一些方法創建一個字符串/數字,這些方法將使用自身(this)來生成 output 值,並且可以在您的代碼中用作普通數字/字符串而無需強制轉換或類似的東西,就像普通的 JS 數字/細繩。

類似數字的東西有自己的價值,但您可以訪問 number.negative 屬性,您將擁有與您的數字等價的負數。 您可以創建一個 class 來擴展您想要使用的原始類型,例如,對於數字,我可以使用:

 class Num extends Number { negative = this * (-1); // I can even add a few methods that receive props to calculate new output values exponential(exp) { let result = 1; while(exp-- > 0) { result *= this; } return result; } } const myNum = new Num(3); console.log('Simple sum: ', 1 + myNum); // outputs 4 console.log('Negative: ', myNum.negative); // outputs -3 console.log('Exponential: ', myNum.exponential(2)); // outputs 9

上面的代碼也適用於字符串。 希望我可以幫助某人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM