代码挑战:创建一个跟踪总对象实例数的类Foo

时间:2016-05-10 22:38:28

标签: javascript

我正在尝试为求职应用程序解决代码挑战,但我感到困惑并希望得到任何帮助。

问题:创建一个具有名为refCount的方法的类Foo。在类或其任何实例上调用refCount应返回存在的实例总数。

示例:

var f1 = new Foo();

f1.refCount(); // should be 1
Foo.refCount(); // should be 1

var f2 = new Foo();

f1.refCount(); //should be 2
f2.refCount(); // should be 2
Foo.refCount(); // should be 2

到目前为止我有这样的事情:

function Foo() {

  this.refCount = function() {
    ++Foo.prototype.refs;
    return Foo.prototype.refs;
  }

}

Foo.prototype.refs = 0;

我也尝试使用IIFE将方法附加到类本身,但后来我无法弄清楚如何创建新实例。

3 个答案:

答案 0 :(得分:2)

无法做到。

JavaScript是面向对象的,JavaScript中的类只是一种幻觉,通过将对象的原型属性设置为某个原型对象来创建。

新的Foo()语法是用于设置原型的语法糖。正如其他人所示,你最好的选择是在构造函数中进行refCounting,有效地计算它被调用的次数。然后,您可以将count变量存储在原型中,或者作为构造函数本身的属性或在IIFE中存储(见下文),并在refCount函数中返回其值。

但是如果人们开始动态地改变对象的原型,那么对象可以改变类,我认为refCount函数无法知道发生了什么。

var Foo

(function(){
  var n = 0;
  Foo = function Foo() {
    this.refCount = Foo.refCount;
    n++;
  };
  Foo.refCount = function() {
    return n;
  }
})()

function Bar() {}

f = new Foo();
console.log("created f, refCount = 1", f instanceof Foo, f.refCount(), Foo.refCount());

g = new Foo();

console.log("created g, refCount = 2", f instanceof Foo, g instanceof Foo, f.refCount(), g.refCount(), Foo.refCount());

g.__proto__ = Bar.prototype;
console.log("turned g into a Bar", f instanceof Foo, g instanceof Foo)
console.log("but refCount still is 2", Foo.refCount());

h = Object.assign(f)
console.log("created h without calling the constructor", h instanceof Foo)
console.log("But refCount still is 2", h.refCount(), Foo.refCount())

See it on JSBin

请参阅https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chainHow to set the prototype of a JavaScript object that has already been instantiated?

答案 1 :(得分:1)

function Foo() {
    Foo.__n++;
}
Foo.refCount = function() { return Foo.__n; }
Foo.__n = 0;
Foo.prototype.refCount = Foo.refCount;

输出:

> var f = new Foo(); console.log(f.refCount(), Foo.refCount());
1 1
> f = new Foo(); console.log(f.refCount(), Foo.refCount());
2 2
> f = new Foo(); console.log(f.refCount(), Foo.refCount());
3 3

答案 2 :(得分:0)

var n = refs = 0;

function refCount() {
  refs = ++n;
  return n;
}

function Foo() {
  refCount()
}

var f1 = new Foo();
console.log(refs);

var f2 = new Foo();
console.log(refs);
相关问题