js創(chuàng)建對象經(jīng)典模式全面了解
來源:易賢網(wǎng) 閱讀:1148 次 日期:2016-08-30 16:19:42
溫馨提示:易賢網(wǎng)小編為您整理了“js創(chuàng)建對象經(jīng)典模式全面了解”,方便廣大網(wǎng)友查閱!

下面小編就為大家?guī)硪黄猨s 創(chuàng)建對象 經(jīng)典模式全面了解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。

1. 概述

通過構(gòu)造函數(shù)創(chuàng)建對象, 有時(shí)忘記了寫new, 這時(shí)函數(shù)就會(huì)返回undefined

可以創(chuàng)建一個(gè)函數(shù)createXXX, 在內(nèi)部封裝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 || {});

}

注意,如果函數(shù)沒有顯示的寫明 return xxx; 則返回undefined。

example

利用構(gòu)造函數(shù)定義Cat,并讓所有的Cat對象有一個(gè)name屬性,并共享一個(gè)方法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 創(chuàng)建對象 經(jīng)典模式全面了解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考

更多信息請查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機(jī)網(wǎng)站地址:js創(chuàng)建對象經(jīng)典模式全面了解
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 加入群交流 | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65317125(9:00—18:00) 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專用圖標(biāo)