我已经玩ES6一段时间了,我注意到虽然声明的变量var按预期提升了......
console.log(typeof name); // undefined
var name = "John";
Run Code Online (Sandbox Code Playgroud)
... 用吊装声明let或const似乎有一些问题的变量:
console.log(typeof name); // ReferenceError
let name = "John";
Run Code Online (Sandbox Code Playgroud)
和
console.log(typeof name); // ReferenceError
const name = "John";
Run Code Online (Sandbox Code Playgroud)
这是否意味着变量声明let或未声明const?这是怎么回事?这个问题let和const这个问题有什么区别吗?
在玩ES6之后,我真的开始喜欢新的语法和功能了,但我确实对类有疑问.
新的ES6类是旧原型模式的语法糖吗?或者幕后还有更多的事情发生在这里?即:
class Thing {
//... classy stuff
doStuff(){}
}
Run Code Online (Sandbox Code Playgroud)
vs:
var Thing = function() {
// ... setup stuff
};
Thing.prototype.doStuff = function() {}; // etc
Run Code Online (Sandbox Code Playgroud) 我有一个小的 vanila-js 项目。Chrome 的控制台给我标题错误。我的代码结构是这样的:
<script type="module">
import * as THREE from 'https://unpkg.com/three/build/three.module.js';
import { TrackballControls } from 'https://unpkg.com/three/examples/jsm/controls/TrackballControls.js';
var camera, scene, renderer, controls;
init();
animate();
function init() {
//code here
var list_of_objects=generate_first();}
class Color{
constructor() {
this.R=getRandomInt(0,255);
this.G=getRandomInt(0,255);
this.B=getRandomInt(0,255);
this.hex=this.fullColorHex(this.R,this.G,this.B);
}
//rest of code}
function generate_first() {
var list_of_gens=[];
var color=new Color();}
</script>
Run Code Online (Sandbox Code Playgroud)
控制台显示上线:var color=new Color();如何解决?我不知道为什么我有这个问题。PS:是的,我在堆栈上搜索了其他主题,但这些主题涉及框架或打字稿。没有人帮助我解决我的错误!这就是我创建该主题的原因。请不要留下缺点或大拇指,但请帮助我。
我最近一直在学习很多Javascript,而且我一直在努力理解提升变量的价值(如果有的话).
我理解(现在)JS是一个双程系统,它编译然后执行.另外,我理解var关键字'exists'在它声明的词法范围内,因此如果在引擎分配值之前调用它,那么为什么它是'undefined'.
问题是,为什么这甚至重要?有什么用途可以提升你不能不提升的变量?我觉得它只会创建不太可读的代码而没有收获......
是否存在提升变量有用的示例?
我知道没有错误,因为类是提前定义的。
class Polygon {
log() { console.log('i am polygon'); }
}
const p = new Polygon(); // no error as I had expected.
p.log();
Run Code Online (Sandbox Code Playgroud)
我也知道这个错误的原因。类没有被提升,所以这个错误是我的预期结果。
const b = new Bolygon(); // Uncaught TypeError as I had expected.
b.log();
class Bolygon {
log() { console.log('i am bolygon'); }
}
Run Code Online (Sandbox Code Playgroud)
在某些情况下,例如这段代码(playground link),类会被提升吗?
我不明白为什么new Hero()不会导致下面的错误。
class Hero被吊起?
class AppComponent {
hero = new Hero('foo') // why no error?
}
class Hero {
constructor(public name: …Run Code Online (Sandbox Code Playgroud) class A {
f1() {
f2();
}
f2() {}
}
var a = new A();
console.log(a.f1());
Run Code Online (Sandbox Code Playgroud)
返回f2未定义.
鉴于:
{
function f1() {
return f2();
}
function f2() {
return 'f2';
}
console.log(f1());
}
Run Code Online (Sandbox Code Playgroud)
打印'f2'
我只是想知道为什么类中的函数没有被提升?