Javascript 获得';未定义';在原型的构造函数中初始化属性时

Javascript 获得';未定义';在原型的构造函数中初始化属性时,javascript,jquery,prototype,Javascript,Jquery,Prototype,我开始使用prototype,如果我使用代码,我会得到预期的结果: $(document).ready(function() { var MyObject = new MyClass(); MyObject.assign(); MyObject.console(); }); function MyClass() { var myProperty; }; MyClass.prototype = { assign: function() {

我开始使用prototype,如果我使用代码,我会得到预期的结果:

$(document).ready(function() {
    var MyObject = new MyClass();

    MyObject.assign();

    MyObject.console();
});

function MyClass() {
    var myProperty;
};

MyClass.prototype = {

    assign: function() {
        this.myProperty = 'Hello world!';
    },

    console: function() {
        console.log(this.myProperty); // Shows 'Hello world!'
    }
};
但是下面的代码返回
未定义的
。我不明白为什么,有人能帮我吗

$(document).ready(function() {
    var MyObject = new MyClass();

    MyObject.console();
});

function MyClass() {
    var myProperty = 'Hello world!';
};

MyClass.prototype = {

    console: function() {
        console.log(this.myProperty); // Shows 'undefined'
    }
};

在第一段代码中,您实际上创建并定义了该属性:
this.myProperty='helloworld!'在此之前,此属性不存在

在第二段代码中,您从未定义属性

将其更改为:

function MyClass() {
    //NOT "var", but "this."
    this.myProperty = 'Hello world!';
};
另一种方法是(如果
myProperty
的值默认为某个值,则将其放入原型中:

MyClass.prototype = {

    //Now all instantiations will have this preset    
    myProperty: "Hello World",

    console: function() {
        console.log(this.myProperty);
    }
};

在第一段代码中,您实际上创建并定义了该属性:
this.myProperty='Hello world!';
在此之前,该属性不存在

在第二段代码中,您从未定义属性

将其更改为:

function MyClass() {
    //NOT "var", but "this."
    this.myProperty = 'Hello world!';
};
另一种方法是(如果
myProperty
的值默认为某个值,则将其放入原型中:

MyClass.prototype = {

    //Now all instantiations will have this preset    
    myProperty: "Hello World",

    console: function() {
        console.log(this.myProperty);
    }
};
试试这个:

据此有关

$(文档).ready(函数(){
var MyObject=new MyClass();
MyObject.console();
});
函数MyClass(){
this.myProperty='Hello world!';
};
MyClass.prototype.console=函数(){
//console.log(this.myProperty);
document.write(this.myProperty);
};
试试这个:

据此有关

$(文档).ready(函数(){
var MyObject=new MyClass();
MyObject.console();
});
函数MyClass(){
this.myProperty='Hello world!';
};
MyClass.prototype.console=函数(){
//console.log(this.myProperty);
document.write(this.myProperty);
};
var
声明局部变量。
var
声明局部变量。