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 function
function Child(name) {
// Check if "static" count exists.
if (typeof Child.count === "undefined") Child.count = 0;
// Assign instance variable
this.name = name;
Child.count++;
}
var alice, bob;
alice = new Child("Alice");
console.log(alice.name) // ==> "Alice"
console.log(Child.count) // ==> 1
bob = new Child("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 variable
var count = 0;
function constructor(name) {
// Public static variable
constructor.likes = ['toys', 'candy', 'pets', 'coloring'];
// Instance variable
this.name = name;
// Accessor methods
this.getCount = function() {
return count;
}
this.getLikes = function() {
return constructor.likes;
}
count++;
}
// Return the constructor function
return constructor;
})()
Post a Comment for "How To Create Instance Variables Explicitly?"