2015年8月16日 星期日

javascript difference between Object.create() and new SomeFunction()

var test = {val: 1, func: function(){ return this.val; }};
var testA = Object.create(test);

testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2

 inherits directly from the one passed as its first argument.


var otherTest = function(){
    this.val = 1;
    this.func = function(){
        return this.val;
    };
};

var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB .val = 2;
console.log(otherTestA.val); // 1 
console.log(otherTestB.val); // 2

console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2
Well, you can create closures, e.g. using property descriptors argument:




from:
http://stackoverflow.com/questions/4166616/understanding-the-difference-between-object-create-and-new-somefunction

沒有留言:

張貼留言