4

The code below will log a, a.length, and b.test. a and b.test both yield [1, 2, 3]. Edit-- I screwed up. b.test yields undefined. See raina's response below.

a.length yields 3.

b.test.length fails with "Cannot read property 'length' of undefined"

Why is this the case when a and b.test are equal?


var a = [1,2,3];

var b = function(){};

b.prototype.test=[1,2,3];

console.log(a);

console.log(a.length);

console.log(b.test);

console.log(b.test.length);

1 Answers1

5

Because b does not have test property - it's a function, and its prototype object is Function.prototype one.

But objects created with this function will have this property in their prototype chain (as prototype property of b points to the object that has test property defined, so this...

console.log(new b().test.length);

... should give you 3, as expected.

raina77ow
  • 103,633
  • 15
  • 192
  • 229