1. Overview
Create an object through a constructor, sometimes forget to write new, and the function will return undefined
You can create a function createXXX to encapsulate new internally.
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 that if the function does not display the return xxx; returns undefined.
example
Use the constructor to define Cat, and let all Cat objects have a name attribute, and share a method says(), returning 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('Doraemon');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 article on the classic js object creation model is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.