简体   繁体   English

在原型构造函数中创建对象引用

[英]Creating object reference in prototype constructor

I'm trying to wrap my head around using Javascript prototype objects and have run into a block perhaps due to my understanding of a traditional classes. 我试图用Javascript原型对象来解决问题,可能由于对传统类的理解而陷入困境。

My code looks like the following: 我的代码如下所示:

$(document).ready(function () {
    var instance = new cards();
    $dom = instance.buildItem(5);
}
var cards = function () {
    //constructor
    this.chromaObj = chroma.scale(["lightblue", "navy"]).domain([2, 6]);
}
cards.prototype.buildItem = function (val) {
    var scale = this.chromaObj;
    var $item = $("<span>" + val + "</span>").addClass("label-default").addClass("label").css({
        "background-color": scale(val)
    });
    return $item;
}

Every time scale is called in the buildItem function, I receive an error in the console that scale is not a function, however, if I create the scale instance inside of the buildItem function, it works as expected. 每次在buildItem函数中调用scale时,都会在控制台中收到一个错误,指出scale不是函数,但是,如果我在buildItem函数内部创建了scale实例,它将按预期工作。

Can someone please point me in the right direction as to why I am unable to access the function reference when it is defined in the constructor? 有人可以向我指出正确的方向,为什么在构造函数中定义函数引用时为什么我无法访问它?

The original code does in fact work correctly. 实际上,原始代码确实可以正常工作。

My problem turned out to be that I was calling buildItem from another method (not shown here) using the generic cards.prototype.buildItem() , which caused a subsequent call to chromaObj to be undefined. 我的问题原来是,我正在使用通用的cards.prototype.buildItem()从另一个方法(此处未显示)调用buildItem ,这导致对chromaObj的后续调用未定义。

The solution was to change all calls to cards.prototype.buildItem() to this.buildItem() . 解决方案是cards.prototype.buildItem()所有调用更改为this.buildItem()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM