例如,我有这么一段Java代码:
public class Test1 {
public String readDB(){
return "example";
}
public String displayData(){
return "This is a"+this.readDB();
}
}
然而当我简单转换为Javascript时就出现问题了:
function Test1(){};
Test1.prototype.readDB = function(){
return 'example';
};
Test1.prototype.displayData = function(){
return 'This is a'+this.readDB();
}
这个this指向的就不是Test1的实例了,就变成了window对象了,我应该如何解决这个问题呢?
谢谢
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这个
this指向的是Test1的实例呀,不知道你为什么说变成了window对象1.如果将构造函数当成函数,就在函数后面直接添加方法,this就指代包裹他的外层函数。
2.如果要实例化构造函数,就像1楼的答案。
因为这个Test1()是构造函数,你要先new过才能调用实例
可以直接返回原型或者new