gpt4 book ai didi

javascript - 安装组件时私有(private)变量不可用

转载 作者:行者123 更新时间:2023-12-03 02:21:19 26 4
gpt4 key购买 nike

示例:

@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 构造函数的一部分被调用,则该变量可以是未定义的。这是一个经过简化设置的演示,可以看到 _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;
}

事件/范围损失

第二种可能性是该方法是由事件调用的,或者是在范围可能丢失的其他情况下:

class Vue {
constructor() {
}
}


class MyVueComponent extends Vue {

private _myVar: string = "not undefined";

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

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

const x = new MyVueComponent();

// Scope Interrupted
window.setTimeout(x.mounted, 20);

在这些情况下,保留范围的箭头函数可以解决问题:

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

关于javascript - 安装组件时私有(private)变量不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49147919/

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