The following code gives error.
var user;
user.load= function () {
//
}
It gives error Cannot read property 'load' of undefined
EDIT: Isn't everything an Object by default in Javascript?
The user
variable needs to be an object in order for you to assign properties to it. Variables that have not been assigned a value are undefined
, and you can't assign properties to 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.
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.
You need to assign an object (a new empty object is fine) to the variable:
var user = {};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.