[英]Why doesn't this edit to a prototype work?
我想在函數構造函數(類)的原型中添加一個常量,但是為了未定義,為什么會回來?
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);
在您的示例中,您將向類原型添加屬性。 只有在實例化該類的對象時才能看到這些。
要實現您想要的,只需依賴expando屬性:
myClass.age = 22;
window.alert(myClass.age);
如果它有用,請將第一個示例視為在C#中聲明類的公共屬性。 您只能在實例化時訪問它。
第二個例子就像在C#中聲明一個類的公共static
屬性。 您無需實例化它即可訪問它。
編輯評論
要從類中的方法中訪問年齡,請使用this
myClass.prototype.GetAge = function(){
alert(this.age);
}
使用something.bar
只有當something
是一個類的實例時才有效。
我創建“類靜態”變量的模式如下所示:
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.