Javascript 安装组件时,专用变量不可用

Javascript 安装组件时,专用变量不可用,javascript,typescript,vue.js,Javascript,Typescript,Vue.js,例如: @Component export default class MyVueComponent extends Vue { private _myVar: string = "not undefined"; constructor() { super(); console.log(this._myVar); } mounted() { console.log(this._myVar); } }

例如:

@Component
export default class MyVueComponent extends Vue {

    private _myVar: string = "not undefined";

    constructor() {
        super();
        console.log(this._myVar);
    }

    mounted() {
        console.log(this._myVar);
    }
}
控制台:

"not undefined"
undefined


我似乎没有找到合适的关键字来搜索这个问题。直觉上它不应该这样做,但很明显我做错了什么/不理解一个基本概念。

这个问题的关键是如何调用
mounted
方法

建造师 如果将其作为
Vue
构造函数的一部分调用,则该变量可能未定义。下面是一个演示,其中有一个简化设置,可以看到
\u myVar
未定义

class Vue {
    constructor() {
        this.mounted();
    }
}


class MyVueComponent extends Vue {

    private _myVar: string = "not undefined";

    constructor() {
        super();
        console.log(this._myVar);
    }

    mounted() {
        console.log(this._myVar);
    }
}

const x = new MyVueComponent();

这是因为生成的构造函数中的顺序如下所示:

function MyVueComponent() {
    var _this = _super.call(this) || this; // <-- _myVar undefined
    _this._myVar = "not undefined"; // <-- and then it gets defined
    console.log(_this._myVar);
    return _this;
}
在这些情况下,保留作用域的箭头函数可以解决以下问题:

const x = new MyVueComponent();
window.setTimeout(() => x.mounted(), 20);

请注意,这不是真正的
私有
成员。这个
挂载
中的价值是什么?@ohgod为什么是的,我知道成员的隐私只在编译器中强制执行。@JamesMonger问得好:在
构造函数中
this=MyVueComponent
而在
mounted
中,this=VueComponent
。虽然我仍然不太明白到底出了什么问题以及如何解决它。将
private\u myVar
更改为
public\u myVar
甚至
\u myVar
都会得到相同的结果:当
挂载
=>
控制台.log(this.\u myVar);//未定义的
“由于生成的构造函数中的顺序”=>即使我删除了该构造函数,
\u myVar
在装入时仍然是
未定义的
。添加构造函数只是为了100%确保
\u myValue
确实不是
未定义的
,而是在
装入之前。正如@JamesMonger在评论中让我意识到的那样:在
构造函数中,
this=MyVueComponent
,而在
挂载中,
this=VueComponent
。另外,
VueRouter
正在处理构造函数,所以我不能使用arrow函数(我想)。我不太明白,我觉得我做错了一些更基本的事情。。。
const x = new MyVueComponent();
window.setTimeout(() => x.mounted(), 20);