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('测试失败!');
}

最新文章

  1. SQL Server 2014新功能PPT
  2. iOS(本地通知与远程通知)
  3. BZOJ 2038 [2009国家集训队]小Z的袜子 莫队
  4. [MySQL] 数据统计 —— 按周,按月,按日分组统计数据
  5. Objective-C Runtime之着魔的UIAlertView
  6. iphone在iframe页面的宽度不受父页面影响,避免撑开页面
  7. jdk源码研究1-HashMap
  8. 用ECMAScript4 ( ActionScript3) 实现Unity的热更新 -- 在脚本中使用MonoBehaviour
  9. python的学习笔记01_6练习
  10. storm+Calcite
  11. Windwos Live Writer插件指南
  12. Fibonacci PKU logn 求斐波那契的快速方法!!!
  13. Python3:if __name__ == '__main__' 详解
  14. 分布式实时日志系统(四) 环境搭建之centos 6.4下hbase 1.0.1 分布式集群搭建
  15. 福大软工 Alpha 事后诸葛亮
  16. idea常用实用快捷键
  17. 【bzoj4894】天赋
  18. go语言基础之for循环
  19. Spring beans.xml
  20. nyoj 742 子串和再续 类似 HDU 1024

热门文章

  1. Spring3 MVC请求参数获取的几种方法
  2. asihttprequest本机调试时正常,发布后闪退
  3. 使用 crosswalk-cordova 打包sencha touch 项目,再也不用担心安卓兼容问题!
  4. zepto - push
  5. CentOS下Redis服务器安装配置
  6. css的两种引用方式 link和@import
  7. C# 事件和委托
  8. win7激活
  9. 从零开始Grunt
  10. web.config中httpRunTime的属性