Javascript Variable Inside Class Is Always Undefined
Solution 1:
This happens because you assume that setting name
in the object retains a reference to the original name
variable. Instead, you want to assign it to the current object (which, you might as well ignore the private variable altogether).
Dog = {
name: '',
setName: function(n) {
this.name = n;
}
};
However, if you want to keep name
private then you create a getter for it instead.
varDog = (function() {
var name;
return {
setName: function(n) {
name = n;
},
get name: function() {
return name;
}
};
})();
Solution 2:
The easy way to fix this is:
Dog = (function() {
var dog = {
setName: setName,
name: name
};
functionsetName(_name) {
dog.name = _name;
}
return dog;
}
In your code, you were setting the wrong name
variable.
var name;
functionsetName(_name) {
name = _name;
}
In this function, setName is setting the internal variable name
and not the property name
. In JavaScript, strings are immutable, so when you change it, it creates a new string, and doesn't update the existing one.
Solution 3:
This might be a better pattern for you. You're using the very old ES3 style constructor.
(function(exports) {
functionDog(name) {
this.name = name;
}
Dog.prototype.speak = function() {
return"woof";
};
// other functions ...exports.Dog = Dog;
})(window);
var d = newDog('Hero');
console.log(d.name); // "Hero"
You might want to look into ES6 classes too
classDog {
constructor(name) {
this.name = name;
}
}
let d = newDog('Hero');
console.log(d.name); // "Hero"
Solution 4:
Sounds like you want to make a constructor... Check this sample:
functionDog(prop) {
this.name = prop.name;
this.color = prop.color;
}
var myDog = newDog({
name:'Sam',
color: 'brown'
});
alert()
console.log('my dog\'s name is: '+myDog.name);
console.log('my dog\'s color is: '+myDog.color);
you can try it here: http://jsfiddle.net/leojavier/ahs16jos/
I hope this helps man...
Solution 5:
Use the 'this' keyword.
Dog = (function() {
var name;
functionsetName(_name) {
this.name = _name;
}
return {
setName: setName,
name: name
};
})();
Dog.setName('Hero');
alert(Dog.name);
Post a Comment for "Javascript Variable Inside Class Is Always Undefined"