欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2016年08月16日 09:14:09   投稿:jingxian  
下面小編就為大家?guī)硪黄猨s 創(chuàng)建對象 經(jīng)典模式全面了解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

1. 概述

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

可以創(chuàng)建一個函數(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

利用構造函數(shù)定義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 創(chuàng)建對象 經(jīng)典模式全面了解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論