leo*_*277 2 javascript ecmascript-6
我最近去面试,遇到一个关于 JAVASCRIPT 的问题,我无法回答,但我真的很想知道答案,但我不知道如何在 google 中表达。
问题是:
var a = new A();
a(); // return 1
a(); // return 2
var b = new A();
b(); //return 1;
b(); //return 2;
Run Code Online (Sandbox Code Playgroud)
实施 A
我如何使用 javascript 解决这个问题。到目前为止我得到了这个
class A {
constructor(){
this.num = 1;
}
function(){
console.log(this.num--);
}
}
Run Code Online (Sandbox Code Playgroud)
使用new 运算符时,类构造函数或函数可以返回this.以外的值。根据 MDN:
构造函数返回的对象成为整个 new 表达式的结果。如果构造函数没有明确返回对象,则使用在步骤 1 中创建的对象。(通常构造函数不返回值,但如果他们想覆盖正常的对象创建过程,他们可以选择这样做。)
所以这个问题的一个可能的答案是从构造函数返回一个函数:
class A {
constructor(){
this.num = 1;
return this.func.bind(this); // bind the function to `this`
}
func() {
console.log(this.num++);
}
}
var a = new A();
a(); // return 1
a(); // return 2
var b = new A();
b(); //return 1;
b(); //return 2;Run Code Online (Sandbox Code Playgroud)
可能的用途:
回答完这个问题后,我开始思考返回值的合法用途。
class Singleton {
constructor() {
if(Singleton.instance) {
return Singleton.instance;
}
Singleton.instance = this;
return this;
}
}
console.log(new Singleton() === new Singleton()); // trueRun Code Online (Sandbox Code Playgroud)
class Module {
constructor(value) {
this.value = value;
return {
increment: this.increment.bind(this),
decrement: this.decrement.bind(this),
getValue: this.getValue.bind(this),
};
}
increment() {
this.value++;
}
decrement() {
this.value--;
}
getValue() {
return this.value;
}
}
const module = new Module(5);
module.increment();
module.increment();
module.decrement();
console.log(module.value); // undefined
console.log(module.getValue()); // 6Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
862 次 |
| 最近记录: |