为什么这个编辑原型不起作用? [英] Why doesn't this edit to a prototype work?
问题描述
我想在函数构造函数(类)的原型中添加一个常量,但它会以未定义的原因返回?
I wanted to add a constant to the prototype of a function constructor (class) but it is coming back as undefined why?
function myClass(){
}
$(document).ready(function(){
myClass.prototype.age = 22;
window.alert(myClass.age);
});
推荐答案
因为它的原型继承。
以下情况可行:
myClass.prototype.age = 22;
var myobj = new myClass();
window.alert(myobj.age);
在您的示例中,您要向类原型添加属性。只有在实例化该类的对象时才会看到这些。
In your example you are adding properties to the class prototype. You only see these when you instantiate an object of that class.
要实现您的目标,只需依赖expando属性:
To achieve what you want, just rely on an expando property:
myClass.age = 22;
window.alert(myClass.age);
如果有用,请将第一个示例视为在C#中声明类的公共属性。您只能在实例化时访问它。
If its helpful, think of the first sample as declaring a public property on a class in C#. You can only access it when you instantiate.
第二个例子就像在C#中声明一个类的公共 static
属性。您不需要实例化它来访问它。
The second example is like declaring a public static
property on a class in C#. You don't need to instantiate it to access it.
编辑评论
访问年龄在类的方法中,使用此此
To access the age from within a method in the class, use this this
myClass.prototype.GetAge = function(){
alert(this.age);
}
这篇关于为什么这个编辑原型不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!