返回JavaScript类值而不是对象引用

tar*_*all 1 javascript

我想知道是否有一种方法可以默认返回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();
Run Code Online (Sandbox Code Playgroud)

现在我想string通过使用myString而不是myString.string.这有可能吗?

编辑

console.log(myString)没有提出问题,因为console.log我的行为是我最初没有考虑到的,这使问题复杂化,这并不意味着什么log.

JLR*_*she 8

你的问题并不完全有意义,但听起来你想要实现这个.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 + "!");
Run Code Online (Sandbox Code Playgroud)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Run Code Online (Sandbox Code Playgroud)

使用ES6类语法:

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

    toString() {
        return this.value;
    }
}

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

console.log(classObj);
console.log(classObj + "!");   
Run Code Online (Sandbox Code Playgroud)

  • @ ikaros45在这个非常简单的情况下没有意义,但是如果对象包含其他东西并且_might_是OP试图得到的东西,那么它是有意义的. (3认同)