js 创建对象 经典模式全面了解
1.概述
通过构造函数创建对象,有时忘记了写new,这时函数就会返回undefined
可以创建一个函数createXXX,在内部封装new。
functionStudent(props){
this.name=props.name||'匿名';
this.grade=props.grade||1;
}
Student.prototype.hello=function(){
alert('Hello,'+this.name+'!');
}
functioncreateStudent(props){
returnnewStudent(props||{});
}
注意,如果函数没有显示的写明returnxxx;则返回undefined。
example
利用构造函数定义Cat,并让所有的Cat对象有一个name属性,并共享一个方法say(),返回字符串'Hello,xxx!':
'usestrict';
functionCat(name){
this.name=name;
}
Cat.prototype.say=function(){
return('Hello,'+this.name+'!');
}
//测试:
varkitty=newCat('Kitty');
vardoraemon=newCat('哆啦A梦');
if(kitty&&kitty.name==='Kitty'&&kitty.say&&typeofkitty.say==='function'&&kitty.say()==='Hello,Kitty!'&&kitty.say===doraemon.say){
alert('测试通过!');
}else{
alert('测试失败!');
}
以上这篇js创建对象经典模式全面了解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。