简体   繁体   English

以下Javascript语句有什么问题?

[英]What is wrong with following Javascript statement?

The following code gives error. 以下代码给出了错误。

var user;

user.load= function () {

//

}

It gives error Cannot read property 'load' of undefined 它给出错误Cannot read property 'load' of undefined

EDIT: Isn't everything an Object by default in Javascript? 编辑:不是默认情况下所有对象都是Javascript对象吗?

The user variable needs to be an object in order for you to assign properties to it. user变量必须是一个对象,以便您为其分配属性。 Variables that have not been assigned a value are undefined , and you can't assign properties to undefined . 未赋值的变量是undefined ,您不能将属性赋给undefined

var user = {};
user.load = function () {
    // ...
}

try this: 尝试这个:

var user = {};

user.load= function () {

//

}
var user = {};
user.load= function () {

//

} 

At the moment user is undefined , where it needs to be an object. 目前,user是undefined ,它需要是一个对象。

var user = {
   load: function(){
        return 'hi';
   }
};
user.load();

or 要么

var user = function(){
   this.load = function(){
      return 'Hi';
   }
}

Isn't everything an Object by default in Javascript? 默认情况下,不是所有对象都是对象吗?

No. Many things are objects, but the default value of a variable is undefined , and that is is a primitive which cannot be assigned properties. 否。很多东西都是对象,但是变量的默认值是undefined ,这是无法分配属性的基元。

You need to assign an object (a new empty object is fine) to the variable: 您需要为该变量分配一个对象(可以使用一个新的空对象):

var user = {};

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

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