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