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

 

posted @ 2016-08-11 18:46  fangfan  阅读(579)  评论(0编辑  收藏  举报