js 创建对象 经典模式全面了解

1. 概述

通过构造函数创建对象, 有时忘记了写new, 这时函数就会返回undefined

可以创建一个函数createXXX, 在内部封装new。

function Student(props){
  this.name = props.name || '匿名';
  this.grade = props.grade || 1;  
}  

Student.prototype.hello = function(){
  alert('Hello, '+ this.name + '!');

}

function createStudent(props){  
  return new Student(props || {});
}

注意 , 如果函数没有显示的写明 return xxx; 则返回undefined。

example

利用构造函数定义Cat,并让所有的Cat对象有一个name属性,并共享一个方法say(),返回字符串'Hello, xxx!':

'use strict';

function Cat(name) {
  this.name = name;
}

Cat.prototype.say = function(){
  return ('Hello, ' + this.name + '!');
}

// 测试:
var kitty = new Cat('Kitty');
var doraemon = new Cat('哆啦A梦');
if (kitty && kitty.name === 'Kitty' && kitty.say && typeof kitty.say === 'function' && kitty.say() === 'Hello, Kitty!' && kitty.say === doraemon.say) {
  alert('测试通过!');
} else {
  alert('测试失败!');
}

以上这篇js 创建对象 经典模式全面了解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。