简体   繁体   English

为什么这个编辑原型不起作用?

[英]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);

});

Because its prototypical inheritance. 因为它的原型继承。

The following would work: 以下将有效:

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. 只有在实例化该类的对象时才能看到这些。

To achieve what you want, just rely on an expando property: 要实现您想要的,只需依赖expando属性:

myClass.age = 22;

window.alert(myClass.age);

If its helpful, think of the first sample as declaring a public property on a class in C#. 如果它有用,请将第一个示例视为在C#中声明类的公共属性。 You can only access it when you instantiate. 您只能在实例化时访问它。

The second example is like declaring a public static property on a class in C#. 第二个例子就像在C#中声明一个类的公共static属性。 You don't need to instantiate it to access it. 您无需实例化它即可访问它。

EDIT FOR COMMENT 编辑评论

To access the age from within a method in the class, use this this 要从类中的方法中访问年龄,请使用this

myClass.prototype.GetAge = function(){
    alert(this.age);
}

Using something.bar only works when something is an instance of a class. 使用something.bar只有当something是一个类的实例时才有效。

My pattern for creating "class static" variables looks like this: 我创建“类静态”变量的模式如下所示:

var MyClass = function() {

    if (typeof this.constructor.static === 'undefined') {
        // create (and initialise) default static variables
        this.constructor.static = { age: 22 };
    }

    // create a local alias
    var static = this.constructor.static;

    // now you can use "static.variableName" as a class static
    alert(static.age);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM