Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/415.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript OOP prototype.method调用this.method_Javascript - Fatal编程技术网

Javascript OOP prototype.method调用this.method

Javascript OOP prototype.method调用this.method,javascript,Javascript,创建对象fn var fn = function() { this.method1 = function() { return this.public; }; this.method2 = function() { return { init: function() { return this.public; } } }; fn.prototype.public =

创建对象fn

var fn = function() {


    this.method1 = function() {

        return this.public;
    };


    this.method2 = function() {

        return {

            init: function() { return this.public; }
        }
    };


    fn.prototype.public = "method prototype";
};
method2()中的this.public原型。init()函数运行返回未定义

有原型的替代品吗?
谢谢。

此问题与
绑定到
method2()
init
函数的不同范围有关,请尝试以下操作:

var object = new fn();

object.method1() // "method prototype"

object.method2().init(); // undefined 
所以


init
函数中的
This
object.method2()
返回的对象,它没有
public
属性。

这有很多错误

但是对您的具体问题的直接回答是调用
init
返回未定义,因为它对
this
的引用是您创建的内部对象,而不是您认为它引用的实例


我建议您停止尝试解决这个特定的问题,学习JavaScript中原型继承的基础知识。

此外,我知道这只是示例代码,但
public
在JavaScript中是一个保留关键字,即使它实际上没有被使用。避免使用保留字作为标识为什么-1?刚才问你一个问题?
this.method2 = function() {
    var self = this;      
    return {
        init: function() { return self.public; }
    }
};
object.method2().init(); // return "method prototype"