簡體   English   中英

返回JavaScript類值,而不是對象引用

[英]Return JavaScript class value instead of object reference

我想知道是否有一種方法可以默認返回JS類的值,而不是引用類對象本身。 舉例來說,我想包裝一個字符串。

var StringWrapper = function(string) {
    this.string = string;
};

StringWrapper.prototype.contains = function (string) {
    if (this.string.indexOf(string) >= 0)
        return true;
    return false;
};

var myString = new StringWrapper("hey there");

if(myString.contains("hey"))
   alert(myString); // should alert "hey there"

if(myString == "hey there") // should be true
   doSomething();

現在我只想通過使用myString而不是myString.string來獲取string 這是可行的嗎?

編輯

我將console.log(myString)排除在了問題之外,因為console.log行為本來就沒有考慮在內,這使問題變得更加復雜,但這並不是關於log

您的問題並不完全有意義,但是聽起來像您想要實現.toString接口:

 var MyClass = function(value) { this.value = value; }; MyClass.prototype.toString = function() { return this.value; }; var classObj = new MyClass("hey there"); snippet.log(classObj); snippet.log(classObj + "!"); 
 <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

使用ES6類語法:

class MyClass {
    constructor(value) {
        this.value = value;
    }

    toString() {
        return this.value;
    }
}

var classObj = new MyClass("hey there");

console.log(classObj);
console.log(classObj + "!");   

暫無
暫無

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

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