In PHP, I have the following class definitions
class my_pet{
public static $name = "paulie";
public static function get_name(){
return static::$name;
}
}
class my_dog extends my_pet{
public static $name = "stacey";
}
When I echo using
echo my_dog::get_name();
I'll get "stacey".
If I change
return static::$name
to
return self::$name;
the answer turns to "paulie".
In JavaScript, I have the following object constructors
function my_pet(){
this.name = "paulie";
}
my_pet.prototype.get_name = function(){
return this.name;
}
function my_dog(){
this.name = "stacey";
}
my_dog.prototype = new my_pet();
my_dog.prototype.constructor = my_dog;
my_pet_instance = new my_dog();
When I call my method using
alert(my_pet_instance.get_name());
I will always get "stacey".
Is there a late static binding equivalent for JavaScript so I can get "paulie" instead of "stacey"?
In your JavaScript code, there's nothing static (or even "static-like").
To simulate static variables, you can attach properties directly to constructors:
function my_pet(){}
my_pet.name = "paulie";
function my_dog(){}
my_dog.name = "stacey";
However, to achieve what you're looking for, you may want to use the prototype chain instead:
function my_pet(){}
my_pet.prototype.name = "paulie";
function my_dog(){
this.name = "stacey";
}
my_dog.prototype = Object.create(my_pet.prototype);
var stacey = new my_dog();
console.log(stacey.name); //stacey
console.log(my_dog.prototype.name); //paulie
delete stacey.name; // no more shadowing
console.log(stacey.name); // paulie
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With