我想将代码添加到函数中,在函数之外,甚至可能在完全不同的 JS 文件中。这可能吗?我怎样才能做到这一点?这是代表我迄今为止尝试过的代码片段:
function myViewModel() {
var self = this;
this.firstName = ko.observable("Mike");
this.lastName = ko.observable("Rassel");
// this was where I was originally making the call
//myViewModel.fullName = ko.computed(function() {
// return self.firstName() + ' ' + self.lastName();
})
}
// this is where the error is happening
myViewModel.fullName = ko.computed(function() {
return self.firstName() + ' ' + self.lastName();
ko.applyBindings(new myViewModel());
更多代码可以查看this JFiddle .
最佳答案
这是向 Javascript 中已定义的构造函数添加方法的方法。
myViewModel.原型(prototype).newFunctionName = function () {};
http://javascriptweblog.wordpress.com/2010/06/07/understanding-javascript-prototypes/
http://timkadlec.com/2008/01/using-prototypes-in-javascript/
关于javascript - 如何向函数主体之外的函数添加代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10649293/