声明后访问对象内的javascript属性

时间:2013-08-15 09:26:28

标签: javascript object knockout.js requirejs

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

提前致谢。

2 个答案:

答案 0 :(得分: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即可。 E.g:

console.log("The password is " + mytestobj.password());

...然后你不依赖于this

请注意,JavaScript函数调用中的this主要由如何调用函数决定,而不是在某些其他语言中定义函数的位置。例如,this此处不会是mytestobj

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

更多:

答案 1 :(得分: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/