OOP JavaScript-参考错误



因此,我试图将我的Web应用程序转换为基于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"

您必须在类定义中正确启动函数:

this.get_string = function(){...}

您的"方法"不是您对象的属性,而是将它们分配给(刺激)全局变量。使用

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

btw,此方法可方便地称为toString,然后将对象铸成字符串时也将使用它。您可能需要使用本地的"私人"变量而不是公共属性.string,这使您的获取者和播放器相当多:

function myObject(string) {
    // the parameter is like 
    // var string;
    this.toString = function() {
        return string;
    };
    this.setString = function(new_string) {
        string = new_string;
    };
}

最新更新