JavaScript 操作符 Optional chaining (?.)
今天查一个问题的时候, 去reivew 别人最近提交的代码, 发现有下面这个改动, 感觉很奇怪, 怎么去掉了为空的短路判断并且中间加了一个问号? 很是疑惑. 难道提交之前碰到键盘了?
再想想, 如果说这样, 本地测试应该就不会过吧, 于是开始怀疑自己. 果不其然, JavaScript 真的有这种操作符.
今天查一个问题的时候, 去reivew 别人最近提交的代码, 发现有下面这个改动, 感觉很奇怪, 怎么去掉了为空的短路判断并且中间加了一个问号? 很是疑惑. 难道提交之前碰到键盘了?
再想想, 如果说这样, 本地测试应该就不会过吧, 于是开始怀疑自己. 果不其然, JavaScript 真的有这种操作符.
let/const 有emporal dead zone (TDZ), 其实这和Java生命使用变量一直, 未声明前不可用. 但var声明但变量一旦进入这个变量声明但function, 即使还没到声明这行代码, 但是这个变量已经有了, 并且赋值为 undefined;
let tmp = true;
if (true) { // enter new scope, TDZ starts
// Uninitialized binding for `tmp` is created
console.log(tmp); // ReferenceError
let tmp; // TDZ ends, `tmp` is initialized with `undefined`
console.log(tmp); // undefined
tmp = 123;
console.log(tmp); // 123
}
console.log(tmp); // true
例子2
if (true) { // enter new scope, TDZ starts
const func = function () {
console.log(myVar); // OK!
};
// Here we are within the TDZ and
// accessing `myVar` would cause a `ReferenceError`
let myVar = 3; // TDZ ends
func(); // called outside TDZ
}
From function expressions in object literals to method definitions;
var obj = {
foo: function () {
···
},
bar: function () {
this.foo();
}, // trailing comma is legal in ES5
}
to
const obj = {
foo() {
···
},
bar() {
this.foo();
},
}
使用 class 和 extend 定义类和继承关系
class Employee extends Person {}
From custom error constructors to subclasses of Error
class MyError extends Error {}
About ECMAScript 6
Strict mode was introduced in ECMAScript 5 to clean up the language.
'use strict';
The bodies of modules and classes are implicitly in strict mode in ECMAScript 6 – there is no need for the 'use strict' marker. Given that virtually all of our code will live in modules in the future, ECMAScript 6 effectively upgrades the whole language to strict mode.
动态加载JS
function loadScript(scriptUrl, callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptUrl;
document.head.appendChild(script);
callback();
}
loadScript("https://code.jquery.com/jquery-3.3.1.min.js", function() {
console.log("loading script");
setTimeout(function () {
console.log("loading done");
//部分DIV 变为整个页面
$("body").html($('#sbo-rt-content').wrap('<p/>').parent().html());
//动态添加CSS
$(document.head).append(`<style>
@media print {
#sbo-rt-content {
background-color: white;
height: 100%;
width: 100%;
position: fixed;
top: 0;
left: 0;
margin: 0;
padding: 15px;
font-size: 14px;
line-height: 18px;
}
}
</style>`);
//打印
window.print();
}, 3000);
});