Property getter/setter and hasOwnProperty

Topics: General
Apr 10, 2014 at 2:53 PM
Hi.

This is a question related to property getters/setters.

I illustrate it with an example.

Given this simple class:
class MyTest 
{
    public A: string = "abc";

    public get B(): string
    {
        return "def";
    }
}
and these unit tests:
describe('hasOwnProperty',
    () =>
    {
        it('finds property A',
            () =>
            {
                var x = new MyTest();
                expect("A" in x).toEqual(true);
                expect(x.hasOwnProperty("A")).toEqual(true);
            });

        it('finds property B',
            () =>
            {
                var x = new MyTest();
                expect("B" in x).toEqual(true);
                expect(x.hasOwnProperty("B")).toEqual(true);    // fails
            });
    });
Check with in operator succeeds in both tests, whereas check for hasOwnProperty will fail for B (which is a property getter).

Why is this the case? I would expect x.hasOwnProperty("B") to succeed.

From a logical point of view a getter/setter should be seen as a property if it is defined within the class.

Any help to clarifiy would be appreciated.

Gianni
Coordinator
Apr 10, 2014 at 3:29 PM
Good question. The difference in behavior is because the A property exists on instances of the class, whereas the B property is defined on the prototype (which is shared among all class instances). You'd see the same behavior if B were a method instead of a property. Note that in the generated code, Object.defineProperty is called on MyTest.prototype rather than on each instance of MyTest.

In the console:
> var x = new MyTest();
undefined
> x.hasOwnProperty('B');
false
> x.__proto__.hasOwnProperty('B');
true
> x.hasOwnProperty('A');
true
> x.__proto__.hasOwnProperty('A');
false
> MyTest.prototype.hasOwnProperty('B');
true
> MyTest.prototype.hasOwnProperty('A');
false