Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why Javascript "typeerror" [closed]

Tags:

javascript

This executes to produce the correct result, and the Chrome debugger says there were no exceptions:

var x = new Foo().bar().baz();

but this goes off into space and never completes, and the Chrome debugger says although bar() executed correctly, it then throws a "typeerror" exception and never gets to the specified function when it attempts to invoke baz():

var x = new Foo();
x = x.bar().baz();

It looks to me like they're functionally identical. Why do they behave differently?

like image 338
Chuck Kollars Avatar asked Mar 22 '23 19:03

Chuck Kollars


1 Answers

Seems to be related to the Chrome debugger:

function Foo(){}

Foo.prototype.bar = function() {
  return this;
}

Foo.prototype.baz = function() {
  return 'baz';
}

var x = new Foo().bar().baz();
console.log(x); // baz

As expected (Firefox, IE, Chrome).

Edit

And also:

var x = new Foo();
x = x.bar().baz()
console.log(x); // baz

The two sets of code are functionally the same.

like image 135
RobG Avatar answered Mar 24 '23 09:03

RobG