gpt4 book ai didi

javascript - OOP Javascript - 引用错误

转载 作者:行者123 更新时间:2023-11-28 09:35:30 25 4
gpt4 key购买 nike

因此,我正在尝试将我的网络应用程序转换为基于 OOP 的应用程序,因为这就是我最初学习编程的方式。我已经定义了所有功能和所有内容,但遇到了问题。

假设我在 index.php 中打开一个脚本标记并创建一个对象函数:

<script type="text/javascript">
function myObject(_string){
this.string = _string;

this.get_string = function(){
return this.string;
}
}
</script>

没什么大不了的。

现在,如果我调用它,如果我这样做,它就可以正常工作:

var my_object = new myObject("this is a string");
console.log(my_object.get_string) // logs "this is a string"

但是如果我将它包装在 domReady 中,则该对象永远不会被创建,并且调用 my_object 会返回引用错误:

$(document).ready(function() {
var my_object = new myObject("this is a string");
console.log(my_object); // returns reference error
});

如果我在对象中嵌入一个函数并尝试调用它,我也会遇到同样的问题:

<script type="text/javascript">
function myObject(_string){
this.string = _string;

this.get_string = function(){
return this.string;
}

this.set_string = function(new_string){
this.string = new_string;
}
}

my_object = new myObject("this is a string");
my_object.set_string("this is a new string"); // returns reference error
my_object.set_string() // Returns reference error
my_object.set_string // returns a string containing the function
</script>

对此感到非常困惑。有人可以帮忙吗?

最佳答案

无论您的代码放置在何处,这都应该有效

function myObject(_string){
this.string = _string;

this.get_string = function(){
return this.string;
};

this.set_string = function(new_string){
this.string = new_string;
};
}

并调用类似的内容:

var my_object = new myObject("this is a string");
console.log(my_object.get_string()) // will log "this is a string"

关于javascript - OOP Javascript - 引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13127842/

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