Complete Understanding of the Classic Mode of js object creation, and comprehensive understanding of js

Source: Internet
Author: User

Complete Understanding of the Classic Mode of js object creation, and comprehensive understanding of js

1. Overview

Create an object through the constructor, and sometimes forget to write new, then the function will return undefined

You can create a createXXX function and encapsulate new in the system.

Function Student (props) {this. name = props. name | 'anonymous'; this. grade = props. grade | 1;} Student. prototype. hello = function () {alert ('hello, '+ this. name + '! ');} Function createStudent (props) {return new Student (props | | {});}

NOTE: If return xxx is not displayed in the function, undefined is returned.

Example

Use the constructor to define Cat and make all Cat objects have a name attribute, share a method say (), and return the string 'hello, xxx! ':

'Use strict '; function Cat (name) {this. name = name;} Cat. prototype. say = function () {return ('hello, '+ this. name + '! ');} // Test: var kitty = new Cat ('Kitty'); var doraemon = new Cat ('doradream'); if (Kitty & kitty. name = 'Kitty '& Kitty. say & typeof kitty. say = 'function' & kitty. say () = 'hello, Kitty! '& Kitty. say === doraemon. say) {alert (' test passed! ');} Else {alert (' test failed! ');}

The above typical object Creation Mode of js has a comprehensive understanding of all the content that xiaobian shares with you. I hope to give you a reference, and I hope you can provide more support to the customer's house.

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.