代码改变世界

JavaScript 继承机制小记

2013-06-27 14:47  straybird  阅读(185)  评论(0编辑  收藏  举报

读《JavaScript: the good parts》, 关于对象继承这块小记一笔:

function Base(v){
    this.baseValue = v;
    this.getBaseValue = function(){
        return this.baseValue;
    };
}

function TestObject(base, c){
    var temp = function(){
        this.content = c;
        this.fromBaseValue = function(){
            return this.baseValue;
        };
    };

    temp.prototype = base;

    return new temp();
}

var b1 = new Base(1);

var t1 = new TestObject(b1, 'this is t1');
var t2 = new TestObject(b1, 'this is t2');

console.log('t1', {'baseValue':t1.baseValue, 'fromBaseValue()': t1.fromBaseValue(), 'getBaseValue()':t1.getBaseValue()})
console.log('t2', {'baseValue':t2.baseValue, 'fromBaseValue()': t2.fromBaseValue(), 'getBaseValue()':t2.getBaseValue()})
//t1 { baseValue: 1, 'fromBaseValue()': 1, 'getBaseValue()': 1 }
//t2 { baseValue: 1, 'fromBaseValue()': 1, 'getBaseValue()': 1 }

b1.baseValue = 2

console.log('t1', {'baseValue':t1.baseValue, 'fromBaseValue()': t1.fromBaseValue(), 'getBaseValue()':t1.getBaseValue()})
console.log('t2', {'baseValue':t2.baseValue, 'fromBaseValue()': t2.fromBaseValue(), 'getBaseValue()':t2.getBaseValue()})
//t1 { baseValue: 2, 'fromBaseValue()': 2, 'getBaseValue()': 2 }
//t2 { baseValue: 2, 'fromBaseValue()': 2, 'getBaseValue()': 2 }

t1.baseValue = 3;
//If we try to retrieve a property value from a object, and if the object lacks the property name,
//then JavaScript attemps to retrieve the property value from the prototype object.
console.log('t1', {'baseValue':t1.baseValue, 'fromBaseValue()': t1.fromBaseValue(), 'getBaseValue()':t1.getBaseValue()})
console.log('t2', {'baseValue':t2.baseValue, 'fromBaseValue()': t2.fromBaseValue(), 'getBaseValue()':t2.getBaseValue()})
//t1 { baseValue: 3, 'fromBaseValue()': 3, 'getBaseValue()': 3 }
//t2 { baseValue: 2, 'fromBaseValue()': 2, 'getBaseValue()': 2 }

b1.baseValue = 4

console.log('t1', {'baseValue':t1.baseValue, 'fromBaseValue()': t1.fromBaseValue(), 'getBaseValue()':t1.getBaseValue()})
console.log('t2', {'baseValue':t2.baseValue, 'fromBaseValue()': t2.fromBaseValue(), 'getBaseValue()':t2.getBaseValue()})
//t1 { baseValue: 3, 'fromBaseValue()': 3, 'getBaseValue()': 3 }
//t2 { baseValue: 4, 'fromBaseValue()': 4, 'getBaseValue()': 4 }