相关疑难解决方法(0)

返回ES6中除类之外的值

最近我一直在用ES6测试类,我注意到在创建类时你不能指定构造函数给出的值.

以前在ES5中这是可能的.

在这两种情况下,我都会实例化类new MyClass .我想这样做是因为我可以返回当前类的子集,只有函数.

ES5 - 返回 My class was init with: Blah

var MyClass = function() {
  this.initVar = 'Blah'

  return 'My Class was init with: ' + this.initVar
}
Run Code Online (Sandbox Code Playgroud)

ES6 - 返回 {}

class Bob {
  constructor() {
   return 'hello' 
  }
}
Run Code Online (Sandbox Code Playgroud)

javascript constructor ecmascript-6

17
推荐指数
1
解决办法
2万
查看次数

返回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.

javascript

1
推荐指数
1
解决办法
598
查看次数

标签 统计

javascript ×2

constructor ×1

ecmascript-6 ×1