我试图在javascript中创建一个类。
define(['knockout', 'knockout-validation', 'jquery'], function(ko, validation, $) {
var SignUpViewModel = {
name: ko.observable().extend({
required: true
}),
email: ko.observable().extend({
required: true,
email: true
}),
password: ko.observable().extend({
required: true
}),
confirmPassword: ko.observable().extend({
areSame: {
params: password,
message: "Repeat password must match Password"
}
}), // this line contains error .
register: function() {}
}
return SignUpViewModel;
});现在它在密码处给出了undefined错误
提前谢谢。
发布于 2013-08-15 12:01:48
对于类创建来说,对象文本并不是最优的。但是他们是一个强大的工具,你可以这样做
(function(app) {
app.define = function (definition) {
definition.prototype = definition.prototype || {};
definition.init.prototype = definition.prototype;
definition.init.prototype.constructor = definition.init;
return definition.init;
};
})(window.app = window.app || {});用它就像
app.define({
init: function() {
this.password = ko.observable().extend({ required: true });
this.confirmPassword = ko.observable().extend({
areSame: {
params: this.password,
message: "Repeat password must match Password"
}
});
},
prototype: {
register: function() {
}
}
});http://jsfiddle.net/ak2Ej/
发布于 2013-08-15 09:29:31
您还没有说明如何调用callitfunction,但如果是这样的话:
mytestobj.callitfunction();...then this.password将在调用中定义。
console.log("The password is " + this.password()); // Since password is a KO observable, it's a function, so use () on it或者,因为这是一个一次性对象,所以只需使用mytestobj.password。例如:
console.log("The password is " + mytestobj.password());...and,那么您就不依赖this了。
注意,this函数调用中的JavaScript主要取决于函数的调用方式,而不是像在其他语言中那样定义函数的位置。因此,例如,在这里,this将不是mytestobj:
var f = mytestobj.callitfunction;
f(); // `this` is not `mytestobj` within the call更多信息:
https://stackoverflow.com/questions/18249829
复制相似问题