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 () {
// ...
}
var user = new Object();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';
}
}
Cannot set a property ("load") on undefinedundefined(the default value of initialized variables) is a primitive value and doesn't have an object equivalent (like strings for example), so autoboxing doesn't take place.var user = 1; user.load = function(){}would work (you just wouldn't be able to access it later... it's complicated).(1).loadis), then the value is first converted to an object by callingToObjectbefore the reference is resolved.