如何使用javascript?_中的.protype(?)使foo().bake()与foo.back()一样工作

How to make foo().bake() works as foo.bake() using .prototype (?) in javascript?_

本文关键字:foo back 工作 一样 bake 中的 protype 何使用 javascript      更新时间:2023-09-26

请看一下这个:

foo = function() {
    document.write("Unicorn <br>");
    return this; //This should return the foo Object every single time
};
//Now when I run foo(), it should display "Unicorn" and it does
foo();
​foo.bake = function() {
    document.write("Baked! <br>");
};
foo.bake();​​​​​​​​​​​​​

​foo.prototype.bake = foo.bake;
​foo().bake();​

我第一次运行foo()时,它按预期写出了"Unicorn"。然后我在现有的foo对象中添加了新的方法(方法bake(),它写着"Baked!",它也起作用。然后我尝试添加相同的方法,但这次使用.protype和IF我正确地理解了它,现在foo().bake应该是与foo.bake相同的函数。

我在StackOverflow上搜索了很多关于jQuery如何同时表现为对象和函数的文章。我阅读并理解了给出的答案,但它们并没有解决我的问题。

我的问题是:如何使foo().bake()foo.bake()一样工作。有可能吗?

提前感谢大家。_

这不是使用构造函数和实例的正确方式

foo = function() {
    document.write("Unicorn <br>");
    /*
    * If foo works as a constructor, "this" refer to the instance.
    * e.g. this.name = 'Foo No.1';
    *
    * If foo works as a function, "this" refer to the current scope which 
    *  is the window object in your case .
    */
    return this; 
};
//Used as constructor
var fooInstance = new foo();
//Used as function
alert(foo() == window)       //alerts true

事实上,您不必在构造函数中返回任何内容,唯一需要做的就是使用new关键字。

因此,在您的案例中,将最后一条语句修改为:(new foo()).bake();

正如@Grant Zhu所指出的,您使用的不是foo的构造函数,而是函数foo。将最后一条语句修改为:(new foo()).bake();解决了问题。

另一种修复它的方法,我发现它非常有用,就是强制一个函数充当构造函数,如下所示:

Something = function() {
  if (false === (this instanceof Something)) {
    return new Something();
  }
  ...
};

Something()的行为与new Something() 完全相同

我不知道你对这个模式有什么看法,我在网上的某个地方找到了它,并从那时起在我的构造函数中使用它。这里有人能看到它有什么问题吗?