0

我正在尝试在 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密码错误

提前致谢。

4

2 回答 2

1

你还没有说你是怎么打电话callitfunction的,但如果是这样的话:

mytestobj.callitfunction();

...然后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());

...然后你不依赖this.

请注意,this在 JavaScript 中,函数调用主要取决于函数的调用方式,而不是像在某些其他语言中那样定义函数的位置。例如,this不会在mytestobj这里:

var f = mytestobj.callitfunction;
f(); // `this` is not `mytestobj` within the call

更多的:

于 2013-08-15T09:29:31.170 回答
1

对象字面量对于类创建来说并不是真正的最佳选择。但它们是一个强大的工具,你可以这样做

(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-15T12:01:48.107 回答