繁体   English   中英

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

[英]Access javascript property inside object after declaration

我想在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错误

提前致谢。

你还没有说过你如何调用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

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

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

更多:

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

(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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM