我有这样的例子.
function Rabbit() {
var jumps = "yes";
};
var rabbit = new Rabbit();
alert(rabbit.jumps); // undefined
alert(Rabbit.prototype.constructor); // outputs exactly the code of the function Rabbit();
Run Code Online (Sandbox Code Playgroud)
我想更改代码,Rabbit()以便var jumps公开.我是这样做的:
Rabbit.prototype.constructor = function Rabbit() {
this.jumps = "no";
};
alert(Rabbit.prototype.constructor); // again outputs the code of function Rabbit() and with new this.jumps = "no";
var rabbit2 = new Rabbit(); // create new object with new constructor
alert(rabbit2.jumps); // but still outputs undefined
Run Code Online (Sandbox Code Playgroud)
为什么不能以这种方式更改构造函数中的代码?
测试.html
<script type="module" src="./B.js"></script>
Run Code Online (Sandbox Code Playgroud)
js
import {bar} from './B.js';
import {test} from './B.js';
export function foo() {
bar();
}
test();
console.log("IN A");
Run Code Online (Sandbox Code Playgroud)
js
import {foo} from './A.js';
export function bar() {
if (Math.random()) {
foo();
}
}
export function test() {
console.log("test");
}
console.log("IN B");
Run Code Online (Sandbox Code Playgroud)
输出是:
B.js:30 test
A.js:24 IN A
B.js:33 IN B
Run Code Online (Sandbox Code Playgroud)
为什么“In B”是执行的最后一行代码?此外,如果在 test.html 中src="./A.js",“IN B”是执行的第一行。
我很惊讶地发现,在Babel中,我可以import互相拥有两个模块而没有任何问题.我发现有一些地方将此称为Babel中已知和预期的行为.我知道这被广泛认为是很多(我猜的是最多)人的反模式,但请忽略这个问题:
有谁知道这是否(或将是)在ES6/7中的正确行为?
我能找到官方答案(和技术解释)最接近的是2ality.com上的评论
javascript circular-dependency ecmascript-6 babeljs ecmascript-7
我知道这一定是非常基本的东西,但我不了解范围是如何工作的。我希望closed整个 JavaScript 文件都知道该变量。
我有类似的东西(在 jQuery 中):
\n\nvar closed = 0;\n\n$(function(){\n console.log(closed);\n});\nRun Code Online (Sandbox Code Playgroud)\n\n但closed被记录为false. load我用和函数尝试了很多东西onload,但失败了。
我在Babel环境中的ES6中遇到了这个问题:
// A.js
class A {
}
export default new A();
// B.js
import C from './C';
class B {
}
export default new B();
// C.js
import A from './A';
import B from './B';
class C {
constructor(A, B){
this.A = A;
this.B = B; // undefined
}
}
export default new C(A, B)
Run Code Online (Sandbox Code Playgroud)
我像这样导入它们:
// stores/index.js
import A from './A';
import B from './B';
import C from './C';
export {
A,
B,
C
}
Run Code Online (Sandbox Code Playgroud)
从我的应用程序入口点我做:
import * as …Run Code Online (Sandbox Code Playgroud) javascript module circular-dependency ecmascript-6 es6-modules
javascript ×5
ecmascript-6 ×3
babeljs ×1
ecmascript-7 ×1
es6-modules ×1
module ×1
oop ×1
prototype ×1
scope ×1
variables ×1