gpt4 book ai didi

javascript - 类方法不能访问属性

转载 作者:搜寻专家 更新时间:2023-11-01 05:03:06 24 4
gpt4 key购买 nike

我创建了一个这样的类:

function MyClass()
{
var myInt = 1;
}

MyClass.prototype.EventHandler = function(e)
{
alert(this.myInt);
}

不幸的是,this是触发事件(在我的例子中是 <a> 标签),我无法访问类属性。

有什么建议吗?

最佳答案

构造函数中声明的“vars”在其他公共(public)函数中不可用,它们被视为“私有(private)成员”。

您可以使用 this.myInt = 1 使成员公开,并可用于所有类方法:

function MyClass(){
this.myInt = 1; // Public member
}

MyClass.prototype.EventHandler = function(e){
alert(this.myInt);
}

或者您可以使用“特权”方法来访问构造函数作用域中的“private”成员:

function MyClass(){
var myInt = 1; // Private member

this.getMyInt = function(){ // Public getter
return myInt;
}
}

MyClass.prototype.EventHandler = function(e){
alert(this.getMyInt());
}

推荐讲座:Private Members in JavaScript (道格拉斯·克罗克福德)

关于javascript - 类方法不能访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/696241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com