简体   繁体   English

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

[英]Access javascript property inside object after declaration

I am trying to make a class in javascript. 我想在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;
});

Now its giving undefined error at password 现在它在密码上给出了undefined错误

Thanks in advance. 提前致谢。

You haven't said how you're calling callitfunction , but if it's like this: 你还没有说过你如何调用callitfunction ,但如果它是这样的话:

mytestobj.callitfunction();

...then this.password will be defined within the call. ...然后this.password将在通话中定义。

console.log("The password is " + this.password()); // Since password is a KO observable, it's a function, so use () on it

Alternately, as that's a one-off object, just use mytestobj.password . 或者,因为这是一个一次性对象,只需使用mytestobj.password Eg: 例如:

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

...and then you're not relying on this . ......然后你不依赖this

Note that this within a JavaScript function call is determined primarily by how the function is called , rather than where the function is defined as in some other languages. 请注意,在JavaScript函数调用中, this主要取决于函数的调用方式 ,而不是在某些其他语言中定义函数的位置。 So for instance, this will not be mytestobj here: 例如, this不是mytestobj

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

More: 更多:

Object literals are not really optimal for Class creation. 对象文字对于类创建来说并不是最佳选择。 But they are a powerful tool, you can do it like this 但它们是一个强大的工具,你可以这样做

(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 || {});

Use it like 像它一样使用它

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/ http://jsfiddle.net/ak2Ej/

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

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