#2 "Распространённые ошибки в JavaScript" Денис Речкунов

Post on 27-Jul-2015

544 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

Transcript

pragmadash Денис РечкуновNode.js-разработчик

Распространённые ошибки в JavaScript

А что если знать

все о JavaScript?

Вот он узнал всё

Много

возможностей

Даже слишком

Большая

ответственность!

Мы должны защитить себя

сами

И так – начнем

Что не так?Constructor.prototype.method = function () {

setTimeout(function () {

this.anotherMethod();

}, 5000);

};

Constructor.prototype.anotherMethod = function () { };

01.

02.

03.

04.

05.

06.

10

this === хозяин метода setTimeoutConstructor.prototype.method = function () {

setTimeout(function () {

this.anotherMethod();

}, 5000);

};

Constructor.prototype.anotherMethod = function () { };

Uncaught TypeError: undefined is not a function

01.

02.

03.

04.

05.

06.

11

this. Решение 1Constructor.prototype.method = function () {

var self = this;

setTimeout(function () {

self.anotherMethod();

}, 5000);

};

Constructor.prototype.anotherMethod = function () { };

01.

02.

03.

04.

05.

06.

07.

12

this. Решение 2Constructor.prototype.method = function () {

setTimeout(function () {

this.anotherMethod();

}.bind(this), 5000);

};

Constructor.prototype.anotherMethod = function () { };

01.

02.

03.

04.

05.

06.

13

Что не так?var index = 123, arr = ['tro', 'lo', 'lo'];

for (var index = 0; index < arr.length; index++) {

arr[index] += 'o';

}

console.log(index);

Output: 123

01.

02.

03.

04.

05.

14

Scope не задается блокомvar index = 123, arr = ['tro', 'lo', 'lo'];

for (var index = 0; index < arr.length; index++) {

arr[index] += 'o';

}

console.log(index);

Output: 3

01.

02.

03.

04.

05.

15

Что не так?var obj = {some: 'first', another: 'second'};

for(var key in obj) {

setTimeout(function () {

console.log(obj[key]);

}, 1000);

}

Output: first second

01.

02.

03.

04.

05.

06.

16

Переменная цикла мутабильнаvar obj = {some: 'first', another: 'second'};

for(var key in obj) {

setTimeout(function () {

console.log(obj[key]);

}, 1000);

}

Output: second second

01.

02.

03.

04.

05.

06.

18

Переменная цикла. Решение 1var obj = {some: 'first', another: 'second'};

for(var key in obj) {

(function (currentKey){

setTimeout(function () {

console.log(obj[currentKey]);

}, 1000);

})(key);

}

01.

02.

03.

04.

05.

06.

07.

08.

19

Переменная цикла. Решение 2var obj = {some: 'first', another: 'second'};

Object.keys(obj)

.forEach(function (key) {

setTimeout(function () {

console.log(obj[key]);

}, 1000);

});

01.

02.

03.

04.

05.

06.

07.

20

Что не так?var some = 'cool and not ';

function foo() {

console.log(some);

var some = 'awful!';

console.log(some);

}

foo();

Output: cool and not awful!

01.

02.

03.

04.

05.

06.

07.

21

Hoistingvar some = 'cool and not ';

function foo() {

console.log(some); // some === undefined

var some = 'awful!';

console.log(some);

}

foo();

Output: undefined awful!

01.

02.

03.

04.

05.

06.

07.

22

Что плохого?for (var index = 0; index < 1000000; index++) {

console.log(index);

}

01.

02.

03.

23

Длинный циклfor (var index = 0; index < 1000000; index++) {

console.log(index);

}

Страница не обрабатывает события

Сервер не принимает новые подключения

01.

02.

03.

24

Длинный цикл. Решениеvar index = 0;

function next() {

if (index >= 1000000) { return; }

console.log(index++);

setTimeout(next, 0);

}

next();

01.

02.

03.

04.

05.

06.

07.

25

Что нет так?var arr = [];

arr[5] = 'some';

console.log(arr.length);

Output: 1

01.

02.

03.

26

length === max(index) + 1var arr = [];

arr[5] = 'some';

console.log(arr.length);

Output: 6

Использовать push/unshift/pop/shift

01.

02.

03.

27

Что нет так?var arr = [];

arr[5] = 'some';

delete arr[5];

console.log(arr.length);

Output: 0

01.

02.

03.

04.

28

undefined x 6var arr = [];

arr[5] = 'some';

delete arr[5];

console.log(arr.length);

Output: 6

Не использовать delete

01.

02.

03.

04.

29

И последний пример

Что не так?function foo () {

return

{

name: 'Batman'

};

}

console.log(foo());

01.

02.

03.

04.

05.

06.

07.

31

Конечно не Batman, он великолепен!function foo () {

return

{

name: 'Batman'

};

}

console.log(foo());

Парсер подставит ';'

01.

02.

03.

04.

05.

06.

07.

32

И вообще советы• Использовать Strict Mode

• Проверять код JShint

• Использовать IDE – WebStorm, например

• Boolean(x), Number(x), String(x) – для приведения типов

• Mozilla Developer Network

33

Вопросы?

top related