Tips
You have to run the following code in the browser, for running from editor like VS Code can't get the wrong
window
orglobal
value
Syntax
var obj = {
name: '123',
getName: function() {
console.log(this.name)
}
}
var getName = obj.getName
var getName1 = obj.getName.bind(obj)
getName()
getName1()
function f1() {
var a = 222
function f2() {
console.log(a)
}
nAdd = function() {
a += 1
}
return f2
}
var obj = f1()
obj()
nAdd()
obj()
var length = 10
function fn() {
console.log('fn: ' + this.length)
}
var obj1 = {
length: 5,
method: function(fn) {
fn()
arguments[0]()
}
}
obj1.method(fn, 1)
var a = 2
function get(a) {
console.log('first time: ' + a)
var a = 1
function a() {}
console.log('second time: ' + a)
}
get(1)
var a = 1
function init(a) {
console.log(a)
var a = 2
function a() {}
console.log(a)
}
init(1)
var length = 10
function getLength() {
console.log(this.length)
}
var obj = {
length: 5,
getLength: function() {
console.log(this.length)
}
}
getLength()
obj.getLength()
var obj = {
name: 'zs',
age: 18,
friends: ['Kate', 'Bob', 'Mike'],
hobby: {
hobby1: 'codes',
hobby2: 'piano'
}
}
function copy(oldObj) {
var newObj = {}
for (var key in oldObj) {
newObj[key] = oldObj[key]
}
return newObj
}
var obj2 = copy(obj)
console.log(obj2.friends === obj.friends)
var obj3 = Object.assign(obj)
console.log(obj3.friends === obj.friends)
var a = 1
function logA() {
console.log(this)
console.log(a)
var a = 2
console.log(this.a)
this.a = 3
}
logA()
new logA()
Promise
new Promise(resolve => {
console.log(1)
resolve()
console.log(2)
}).then(() => {
console.log(3)
})
new Promise(() => {
console.log(4)
}).then(() => {
console.log(5)
})
const original = Promise.resolve(2)
new Promise(resolve => {
resolve(original)
Promise.resolve().then(() => Promise.resolve().then(() => console.log(1)))
console.log(4)
}).then(t => console.log(t))
console.log(3)
async function foo() {
console.log('1')
await bar()
console.log('3')
}
function bar() {
return new Promise(resolve => {
console.log('5')
resolve()
console.log('7')
})
}
;(async () => {
await foo()
})()
const promise = Promise.resolve(2)
new Promise(resolve => {
resolve(promise)
Promise.resolve().then(() => Promise.resolve().then(() => console.log(1)))
console.log(4)
}).then(t => console.log(t))
console.log(3)
网友评论