亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

js 創(chuàng)建對(duì)象 經(jīng)典模式全面了解

 更新時(shí)間:2016年08月16日 09:14:09   投稿:jingxian  
下面小編就為大家?guī)?lái)一篇js 創(chuàng)建對(duì)象 經(jīng)典模式全面了解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

1. 概述

通過(guò)構(gòu)造函數(shù)創(chuàng)建對(duì)象, 有時(shí)忘記了寫(xiě)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ù)沒(méi)有顯示的寫(xiě)明 return xxx; 則返回undefined。

example

利用構(gòu)造函數(shù)定義Cat,并讓所有的Cat對(duì)象有一個(gè)name屬性,并共享一個(gè)方法say(),返回字符串'Hello, xxx!':

'use strict';

function Cat(name) {
  this.name = name;
}

Cat.prototype.say = function(){
  return ('Hello, ' + this.name + '!');
}

// 測(cè)試:
var kitty = new Cat('Kitty');
var doraemon = new Cat('哆啦A夢(mèng)');
if (kitty && kitty.name === 'Kitty' && kitty.say && typeof kitty.say === 'function' && kitty.say() === 'Hello, Kitty!' && kitty.say === doraemon.say) {
  alert('測(cè)試通過(guò)!');
} else {
  alert('測(cè)試失敗!');
}

以上這篇js 創(chuàng)建對(duì)象 經(jīng)典模式全面了解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論