1

I am using "constructor chaining" to define a base class (Super).

function Super () {
  this.member1 = 'superMember1';
  this.member2 = 'superMember2';
}

function Sub() {
  Super.call(this, arguments);
  this.member3 = 'subMember3';
  var t = this.hasOwnProperty("member1"); // gives me true, so I cannot use it
}

How can I test whether a member (1,2,3) is defined (belonging) in my Sub class or in the Super class?

Remark: `this["name"]' is not the way, because I can only decide whether a value has been assigned - not if it is belonging to Super or Sub.

As Darhazer comments below, constructor chaining copies the members, so it might be tricky.

Community
  • 1
  • 1
Horst Walter
  • 13,663
  • 32
  • 126
  • 228

3 Answers3

2

use hasOwnProperty() to check if the member is defined in the current class. If not -obviously it's defined by superclass.

Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
  • Unfortunately this is *not* working, because this.hasOwnProperty("member1"); gives me true in Sub. Did anybody test this, because I appreciate the answer, but it is not working and already got 2 votes. So I either do something wrong, or the answer is not applicable to my scenario. – Horst Walter Aug 30 '11 at 20:04
  • @Horst Walter Well it seems it's well documented in the constructor chaining topic, the properties are copied and hasOwnProperty returns true; this works only for prototype-based inheritance :( – Maxim Krizhanovsky Aug 30 '11 at 20:06
  • Yep, I agree with this, this is why I am asking whether there is some way to find this out - but I could explicitly outline this already in the question, good hint. Also I inherit - in the real world code - from > 1 class, so I need this chaining. However, i appreciated your feedback. – Horst Walter Aug 30 '11 at 20:10
0

You can check for undefined

if (typeof this.member1 == "undefined") {
    //undefined
}
Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
  • This does not work, because if the value remains sometimes undefined (no value assigned ) in Super it fails. – Horst Walter Aug 30 '11 at 19:54
  • For the record, I don't think you should be leaving values unassigned, but set them to `null`. However, if you need to do that, @Darhazer's answer should work. – Alex Turpin Aug 30 '11 at 19:57
0

Obviously as of the answers so far, not possible. Hence will be closed.

Horst Walter
  • 13,663
  • 32
  • 126
  • 228