JavaScript 學習筆記 - 對象和繼承

本文是JavaScript The Good Part 有關對象和繼承的學習筆記。chrome

1. Object.createapp

本函數是ECMAScript 5中的標準函數,其做用是用一個對象做爲原型來生成另外一個對象,能夠用如下的code 模擬實現。函數

 

    if(typeof Object.create !== 'function') {
        Object.create = function(proto){
            var F = function(){};
            if(typeof proto !== 'object'){
                //Follow the chrome error pattern.
                throw new TypeError('Object prototype may only be an Object or null: ' + proto);
            }
            F.prototype = proto;
            return new F();
        };
    }

 

  

具體的想法就是利用一個內部的函數做爲委託,將所需的新對象和原來的對象隔離開來。學習

關於出錯處理是根據Chrome如今的錯誤信息生成的。this

2. newspa

new 是JavaScript裏面的一個關鍵字,其具體的做用,請參考 MDN。 能夠用如下的Code進行模擬。
prototype

 

    _new = function(constructor, args){
        var that = Object.create(constructor.prototype), 
            other = constructor.apply(that, args);
        return (typeof(other) === 'object' && other) || that;
    }

 

 3. 繼承code

3.1 僞傳統方式 (Pseudoclassical)對象

書中並無推薦這種模擬傳統繼承的方式。由於它偏離了JavaScript原型繼承的特性。blog

3.2 原型(Prototypal)

其示例代碼以下所示。

var myMammal = {
    name : 'Herb the Mammal',
    get_name : function ( ) {
    return this.name;
    },
    says : function ( ) {
    return this.saying || '';
    }
};

var myCat = Object.create(myMammal);
myCat.name = 'Henrietta';
myCat.saying = 'meow';
myCat.purr = function (n) {
    var i, s = '';
    for (i = 0; i < n; i += 1) {
        if (s) {
            s += '-';
        }
        s += 'r';
    }
    return s;
};
myCat.get_name = function ( ) {
    return this.says( ) + ' ' + this.name + ' ' + this.says( );
};

 

子類不會擁有父類構造函數中的屬性和方法,不過沒有對類型中的私有變量進行保護。

3.3 函數(Functional)

var constructor = function (spec, my) {
  var that, other private instance variables;
  my = my || {};
  Add shared variables and functions to my
  that = a new object;
  Add privileged methods to that
  return that;
};

加粗的地方須要替換成實際的代碼。

須要說明的地方以下。

  • spec是構造對象所需的信息。
  • my是構造函數能夠分享給其餘對象的信息,不是必需的。
  • 構造一個對象(a new object)能夠是字面量,使用new構造,使用Object.create,調用其餘返回對象的函數。
  • 函數內部的私有屬性是外部不能看到的。
  • 添加私有函數的方法以下所示。
var methodical = function ( ) {
    ...
};
that.methodical = methodical;

例如咱們在調用methodical的時候,就直接使用內部的methodical,而不使用that.methodical,這樣能夠防止此函數被篡改掉。

書中的例子以下。

vvar mammal = function (spec) {
    var that = {};
    that.get_name = function ( ) {
        return spec.name;
    };
    that.says = function ( ) {
        return spec.saying || '';
    };
    return that;
};
var myMammal = mammal({name: 'Herb'});
    var cat = function (spec) {
    spec.saying = spec.saying || 'meow';
    var that = mammal(spec);
    that.purr = function (n) {
        var i, s = '';
        for (i = 0; i < n; i += 1) {
            if (s) {
                s += '-';
            }
            s += 'r';
        }
        return s;
    };
    that.get_name = function ( ) {
        return that.says( ) + ' ' + spec.name + ' ' + that.says( );
    }
    return that;
};
var myCat = cat({name: 'Henrietta'});
相關文章
相關標籤/搜索