源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2021-06-12 17:30 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:js 创建对象 经典模式全面了解
[b]1. 概述[/b] 通过构造函数创建对象, 有时忘记了写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。 [b]example[/b] 利用构造函数定义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 创建对象 经典模式全面了解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部