How To Create Instance Variables Explicitly?
I use a custom framework as such: var SForm = $A.support({ Name: 'SForm', // instance based // hidden, created by using this // static based S: { g
Solution 1:
I'm not quite sure what your question is asking, but looking at your previous questions it looks like you're either avoiding, or are not aware of, the object oriented nature of JavaScript?
Here's an example, I hope it helps you.
// Define constructor functionfunctionChild(name) {
// Check if "static" count exists.if (typeofChild.count === "undefined") Child.count = 0;
// Assign instance variablethis.name = name;
Child.count++;
}
var alice, bob;
alice = newChild("Alice");
console.log(alice.name) // ==> "Alice"console.log(Child.count) // ==> 1
bob = newChild("Bob");
console.log(alice.name) // ==> "Bob"console.log(Child.count) // ==> 2
Update: Using closures
If you really want have private variables that inaccessible outside of the function, you can use a closure to limit the scope of the variable to that scope.
var Child = (function() {
// Private static variablevar count = 0;
function constructor(name) {
// Public static variableconstructor.likes = ['toys', 'candy', 'pets', 'coloring'];
// Instance variablethis.name = name;
// Accessor methodsthis.getCount = function() {
return count;
}
this.getLikes = function() {
returnconstructor.likes;
}
count++;
}
// Return the constructor functionreturnconstructor;
})()
Post a Comment for "How To Create Instance Variables Explicitly?"