I see.... sorry to be so insisting, but I have the class-instance (or class-object) way of thinking so etched in my mind that it's hard to think of templates or objects inheriting from objects. The Javascript way to work with objects is so flexible that it's really confusing.
So in the example above, john and lucy are first created with a "template" (the Person constructor). Both of them are assigned a method called sayHello() by prototyping their "template". Then john's sayHello() method is overridden, not affecting the inheritance in lucy. Is this correct?
Let me ask you a last question regarding the example you wrote about caching using a closure. How come it works (I've tested it and it does work) if the outer function doen't have the num parameter defined? (note the comments I added to the code)
PHP Code:
var isPrime = (function(){ // no argument assigned
var cache = [];
function isPrime(num){
if(cache[num] != null){
return cache[num];
}
var prime = num != 1;
for(var i=2; i<num; i++){
if(num % i == 0){
prime = false;
break;
}
}
cache[num] = prime;
return prime;
}
return isPrime; // call to isPrime without a parameter? My logic says it should be: return isPrime(num)
}()); // self-executing function
The outer (closure) function is self-executing and returning the inner the inner function. The global isPrime becomes the inner isPrime function.
The scope of the outer function is preserved and can still be accessed by the inner function.
Another way to write it:
Code:
(function(){
var cache = [];
isPrime = function isPrime(num){ // create a global variable called isPrime pointing to the inner function
if(cache[num] != null){
return cache[num];
}
var prime = num != 1; // Everything but 1 can be prime
for(var i=2; i<num; i++){
if(num % i == 0){
prime = false;
break;
}
}
cache[num] = prime;
return prime;
}
}()); // self-execute
Yes, that's correct, but I was trying to understand the structure of Kever's example. I suppose that what the isPrime variable is referencing to is the isPrime function (a reference to the function itself is what is returned in the anonymous function), so that if you call isPrime(5) you're referencing it and passing it the parameter. It was kind of twisted because of using the same name for a variable and a function.
I think it's enough with this thread. Thanks a lot everyone for your help!
Bookmarks