调用添加到函数原型中的函数

Invoking a function added to the function prototype

本文关键字:函数 原型 调用 添加      更新时间:2023-09-26

我目前对function.prototype感到困惑。我见过这样的代码:

define([], function() {
    function HomeViewModel(route) {
        this.message = ko.observable('Welcome to Home!');
        }
        HomeViewModel.prototype.doSomething = function() {
            this.message('You invoked doSomething() on the viewmodel.');
        };
        return HomeViewModel;
    }
}

如何在函数原型中添加函数?我也在这里读了一些:function。prototype。在Description部分,它声明:

函数对象继承自Function.prototype。函数。原型不能修改。

但是上面的代码看起来像是在函数原型中添加一个函数。我已经测试过了,上面的代码返回函数HomeViewModel()。如何调用 homeviewmodel。prototype。doSomething从返回值还是实际函数之外?

区别在于functionFunction之间的大写:在Javascript中,你绝对可以向函数的原型添加方法,你只是不能将方法添加到Function.prototype - Function作为"基类",其名称为function,其中有许多内置方法,所有函数共享。

如果你在一个对象原型中添加一个方法,你调用它就像调用你在构造函数中添加的方法一样:

function Test() {
  this.myMethod = function() {
    return true;
  }
}
t = new Test();
t.myMethod();

与一个方法添加到原型:

function Test() {
}
Test.prototype.myMethod = function() {
  return true;
}
t = new Test();
t.myMethod();

那么区别在哪里呢?如果在构造函数中添加方法,则从该构造函数创建的每个对象都将获得该方法的唯一副本:

function Test() {
  this.myMethod = ko.observable();
}
a = new Test();
b = new Test();
a.myMethod('foo');
b.myMethod(); // returns undefined
另一方面,添加到原型中的方法在从该构造函数创建的所有对象之间共享:
function Test() {
}
Test.prototype.myMethod = ko.observable();
a = new Test();
b = new Test();
a.myMethod('foo');
b.myMethod(); // returns 'foo'