codecamp

类及对象构建算法挑战

方法一:

var Person = (function() {
    var name;
    return function(firstAndLast){
      name=firstAndLast;
      this.getFullName=function(){
        return name;
      };
      this.getLastName=function(){
        var arr=name.split(" ");
        return arr[1];
      };
      this.getFirstName=function(){
        var arr=name.split(" ");
        return arr[0];
      };
      this.setFirstName=function(first){
        var arr=name.split(" ");
        arr[0]=first;
        return name=arr.join(" ");
      };
      this.setLastName=function(last){
        var arr=name.split(" ");
        arr[1]=last;
        return name=arr.join(" ");
      };
      this.setFullName=function(firstAndLast){
        return name=firstAndLast;
      };
    };    
})();


var bob = new Person('Bob Ross');
bob.getFullName();

方法二:

var Person = function(firstAndLast) {
    var arr = firstAndLast.split(' '),
        first = arr[0],
        last = arr[1],
        fullName = firstAndLast;
    this.getFirstName = function(){
      return first;
    };
    this.getLastName = function(){
      return last;
    };
    this.getFullName = function(){
      return fullName;
    };  
    this.setFirstName = function(f){
      first = f;
      fullName = first + ' ' + last;
    };
    this.setLastName = function(l){
      last = l;
      fullName = first + ' ' + last;      
    };  
    this.setFullName = function(fn){
      arr = fn.split(' ');
      fullName = fn;
      first = arr[0];
      last = arr[1];
    }; 
};


var bob = new Person('Bob Ross');
bob.getFullName();

日期改写算法挑战
轨道周期算法挑战
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

HTML5&CSS

JavaScript

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }