2
private mouseHover:MouseEventHandler<HTMLElement> = new MouseEventHandler<HTMLElement>();
public get onMouseHover():  MouseEventHandler<HTMLElement> { return this.mouseHover; }

For the above code, I don't understand the 'get' keyword. Could anyone teach me the relative knowledge and give me examples? Thanks!

1
  • 1
    it creates a read only accessor. Commented Jan 15, 2015 at 1:19

3 Answers 3

4

Could anyone teach me the relative knowledge and give me examples?

It allows you define a getter : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

Basically the function onMouseOver gets called when someone accesses the property e.g. console.log(onMouseOver)

Sign up to request clarification or add additional context in comments.

Comments

1

In essence it allows you to control what happens when the property is gotten

In the example code you are tying to understand you have a private property mouseHover. This cannot be accessed outside the class it is defined. The author wanted a to make the mouseHover property accessible outside the class -- without allowing it to be overwritten -- in essence Read Only.

So the author exposed the private mouseHover property using the 'get' keyword on a new property onMouseHover. Using get the author can tell JavaScript what to do when the property is read. As you can see it just returns the backing property.

This gets compiled into the following JavaScript

Object.defineProperty(YourClass.prototype, "onMouseHover", {
    get: function () {
        return this.mouseHover;
    },
    enumerable: true,
    configurable: true
});

To understand this better, look at the documentation for Object.defineProperty https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Comments

-1
class SomeObject {

    public getFoo () {
        return 'foo';
    }

    public get foo () {
        return 'foo';
    }
}

var obj = new SomeObject();

// True
obj.getFoo() === obj.foo;

// Does nothing
obj.foo = 'bar';

// Still true
obj.getFoo() === obj.foo;

// Does nothing
delete obj.foo;

// Still true
obj.getFoo() === obj.foo;

// Does nothing
SomeObject.prototype.foo = 'bar';

// Still true
obj.getFoo() === obj.foo;

// It's gone from all instances of SomeObject
delete SomeObject.prototype.foo;

// True
typeof obj.foo === 'undefined';

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.