在PHP中,我有以下类定义
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"; }当我回声使用
echo my_dog::get_name();我会得到“斯泰西”。
如果我改变
return static :: $ name
至
return self :: $ name;
答案转向“保利”。
在JavaScript中,我有以下对象构造函数
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();当我用我的方法调用时
警报(my_pet_instance.get_name());
我将永远得到“斯蒂西”。
是否有一个晚期静态绑定相当于JavaScript所以我可以得到“paulie”而不是“stacey”?
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"?
最满意答案
虽然JavaScript中的语义和机制不同,但您仍然可以从原型对象访问name属性的子类值。 尝试将此行添加到代码的末尾:
my_dog.prototype.name; // returns "paulie"While the semantics and mechanism are different in JavaScript, you can still access the sub-class value of the name property from the prototype object. Try adding this line to the end of your code:
my_dog.prototype.name; // returns "paulie"更多推荐
发布评论