JavaScript等效的后期静态绑定(JavaScript Equivalent of Late Static Binding)

系统教程 行业动态 更新时间:2024-06-14 16:52:52
JavaScript等效的后期静态绑定(JavaScript Equivalent of Late Static Binding)

在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"

更多推荐

本文发布于:2023-04-05 12:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/58da529c58e6eb84f4540d80a65e9b81.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   静态   后期   JavaScript   Binding

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!