2016-03-03 41 views
0

我越来越熟悉JavaScript的原型世界和this关键字。我是网络世界的新手。今天,当我开始玩原型时,我看到一些奇怪的行为,但我无法弄清为什么会发生这种情况。我创建了一个构造函数Group如下:JavaScript:为什么要获取最后插入的值?

// Code goes here 
function Group(config) { 
    this.config = config; 
    this.getId = function() { 
    return this.config.id; 
    }; 
    this.setId = function(id) { 
    this.config.id = id; 
    }; 
} 

我用它在一个MyGroup构造是这样的:

function MyGroup(config) { 
    var myAttrs = ['id', 'name']; 
    this.g = new Group(config); 
    addGetterSetter(MyGroup, this.g, myAttrs) 
} 

addGetterSetter是我写的getter和setter添加到动态的属性功能MyGroup

var GET = 'get', 
    SET = 'set'; 

function capitalize(str) { 
    return str.charAt(0).toUpperCase() + str.slice(1); 
} 

function addGetterSetter(constructor, target, attrs) { 

    function addGetter(constructor, target, attr) { 
    var method = GET + capitalize(attr); 
    constructor.prototype[method] = function() { 
     return target[method](); 
    }; 
    } 

    function addSetter(constructor, target, attr) { 
    var method = SET + capitalize(attr); 
    constructor.prototype[method] = function(value) { 
     return target[method](value); 
    }; 
    } 
    for (var index = 0; index < attrs.length; index++) { 
    addGetter(constructor, target, attrs[index]); 
    addSetter(constructor, target, attrs[index]); 
    } 
} 

现在,当我使用MyGroupGroup这样的:

var items = [{ 
    id: 123, 
    name: 'Abc' 
}, { 
    id: 131, 
    name: 'Bca' 
}, { 
    id: 22, 
    name: 'bc' 
}]; 
var groups = []; 
items.forEach(function(item) { 
    var g = new MyGroup(item); 
    groups.push(g); 
}); 

groups.forEach(function(g) { 
    console.log(g.getId()); //don't know why this logs 22 three times instead of all ids 
}); 

group.forEach我不知道为什么最后一个项目的id是越来越记录。我无法理解发生了什么问题。我将如何获得g.getId()被调用的组。这是plunkr

+0

在的script.js的线14我得到以下错误:'类型错误:目标[方法]是不是一个function'。看起来'getName'方法不能像你期望的那样创建。 –

+0

它为我工作。不知道为什么它不适合你。 –

回答

3

这是因为你正在向原型中添加方法,并且每当前一个函数在循环中覆盖时,函数会在forEach循环结束时保持对最后一个对象的引用。你需要的是增加功能到该对象:

function MyGroup(config) { 
    var myAttrs = ['id', 'name']; 
    this.g = new Group(config); 
    addGetterSetter(this, this.g, myAttrs) 
} 
function addGetterSetter(object, target, attrs) { 

    function addGetter(object, target, attr) { 
    var method = GET + capitalize(attr); 
    object[method] = function() { 
     return target[method](); 
    }; 
    } 

    function addSetter(object, target, attr) { 
    var method = SET + capitalize(attr); 
    object[method] = function(value) { 
     return target[method](value); 
    }; 
    } 
    for (var index = 0; index < attrs.length; index++) { 
    addGetter(object, target, attrs[index]); 
    addSetter(object, target, attrs[index]); 
    } 
} 

JSFIDDLE

+0

明白了兄弟。非常感谢你。你可以分享一个好的链接,我可以找到JS原型的详细解释吗?我需要充分理解它。 –

+0

请尝试[google](https://www.google.pl/search?sclient=psy-ab&site=&source=hp&btnG=Search&q=understanding+javascript+prototype&oq=&gs_l=&pbx=1) – jcubic

+0

好的。我会做:D –