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.