Implement multicast events and attribute settings/readers in JavaScript

Source: Internet
Author: User
I did an interesting experiment. On the Internet, most of them use functions (like person. getName () and person. setName. Of course, this is a general method. But in a non-IE browser, you can try to run the following code: viewsourceprint? FunctionPerson () & nbsp; {& nbsp

I did an interesting experiment. On the Internet, most of them use functions (like person. getName () and person. setName. Of course, this is a general method.

But in a non-IE browser, you can try to run the following code:

View sourceprint? Function Person ()

{

Var _ name

, _ Age, _ sex;

Var _ nameChanged = new Array ();

This. _ defineGetter _ (NameChanged, function ()

{

Return _ nameChanged;

});

This. _ defineSetter _ (NameChanged, function (value)

{

_ NameChanged. push (value );

});

This. _ defineGetter _ (Name, function ()

{

Return _ name;

});

This. _ defineSetter _ (Name, function (value)

{

If (this. NameChanged! = Null)

{

For (var f in _ nameChanged)

{

_ NameChanged [f] (value );

}

}

_ Name = value;

});

This. _ defineGetter _ (Age, function ()

{

Return _ age;

});

This. _ defineSetter _ (Age, function (value)

{

_ Age = value;

});

}

Person. prototype =

{

Get Sex ()

{

Return _ sex;

},

Set Sex (value)

{

_ Sex = value;

}

};

Var person = new Person ();

Person. NameChanged = function ()

{

Alert (Event 1 );

}

Person. NameChanged = function ()

{

Alert (Event 2 );

}

Person. Name = Treenew;

Person. Age = 22;

Person. Sex = Man

Alert (The + person. Name + Age is + person. Age +. The Sex Value is + person. Sex );

Alert (person. _ sex); // undefined

Therefore, it is elegant to use javascript to implement attributes and events in the object-oriented model. But do you have any idea about multicast events?

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.