Jiahonzheng's Blog

JavaScript 易错题积累

字数统计: 310阅读时长: 1 min
2018/03/26 Share
1
2
3
var person = new Object();
person.name = "Nicholas";
console.log(person.name); // "Nicholas"
1
2
3
var name = "Nicholas";
name.age = 27;
console.log(name.age); // undefined
1
2
3
4
var obj1 = new Object();
var obj2 = obj1;
obj1.name = "Nicholas";
console.log(obj2.name); // "Nicholas"
1
2
3
4
5
6
7
function setName(obj) {
obj.name = "Nicholas";
}

var person = new Object();
setName(person);
console.log(person.name); // "Nicholas"
1
2
3
4
5
6
7
8
9
function setName(obj) {
obj.name = "Nicholas";
obj = new Object();
obj.name = "Greg";
}

var person = new Object();
setName(person);
console.log(person.name); // "Nicholas"
1
2
3
4
5
if (true) {
var color = "blue";
}

console.log(color); // "blue"
1
2
3
var values = [0, 1, 5, 10, 15];
values.sort();
console.log(values); // 0,1,10,15,5

Function Declaration Hoisting

1
2
3
4
console.log(sum(10, 10)); // 20
function sum(num1, num2) {
return num1 + num2;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function factorial(num) {
if (num <= 1) {
return 1;
} else {
return num * factorial(num - 1);
}
}

var anotherFactorial = factorial;

factorial = function() {
return 0;
};

console.log(anotherFactorial(5)); // 0
console.log(factorial(5)); // 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function factorial(num) {
if (num <= 1) {
return 1;
} else {
return num * arguments.callee(num - 1);
}
}

var anotherFactorial = factorial;

factorial = function() {
return 0;
};

console.log(anotherFactorial(5)); // 120
console.log(factorial(5)); // 0
1
2
3
var s1 = "some text";
var s2 = s1.substring(2);
console.log(s2); // me text
1
2
3
var s1 = "some text";
s1.color = "red";
console.log(s1.color); // undefined
1
2
3
var falseObject = new Boolean(false);
var result = falseObject && true;
console.log(result);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function foo() {
console.log(this.a);
}

function doFoo(fn) {
fn();
}

var obj = {
a: 2,
foo: foo
};

var a = "oops, global";
doFoo(obj.foo); // "oops, global"
1
2
3
4
5
6
7
8
9
10
11
12
13
function foo1() {
this.a = 1;
}
function foo2() {
this.a = 2;
return {
a: 3
};
}
var a = new foo1();
var b = new foo2();
console.log(a);
console.log(b);
CATALOG