最近我一直在用ES6测试类,我注意到在创建类时你不能指定构造函数给出的值.
以前在ES5中这是可能的.
在这两种情况下,我都会实例化类new MyClass
.我想这样做是因为我可以返回当前类的子集,只有函数.
My class was init with: Blahvar MyClass = function() {
this.initVar = 'Blah'
return 'My Class was init with: ' + this.initVar
}
Run Code Online (Sandbox Code Playgroud)
{}class Bob {
constructor() {
return 'hello'
}
}
Run Code Online (Sandbox Code Playgroud) 我想知道是否有一种方法可以默认返回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.