无法读取JSON中的父属性

时间:2014-01-14 20:33:42

标签: javascript jquery json

为什么它不起作用?

我收到此错误消息:

  

TypeError:无法读取未定义

的属性'width'
var option = jQuery.extend({
    parent: this,
    width:  280,
    height: 280,

    circle: {
        x:          (option.width / 2) + 5,   // <= HERE!
        y:          (option.height / 2) + 22, // <= AND ALSO HERE!
        radius:     70,
        speed:      5,
        rotation:   0,
        angleStart: 270,
        angleEnd:   90,
        hue:        220,
        thickness:  15,
        blur:       20
    }
}, options);

我如何阅读“父母”财产? 我应该使用另一个前缀吗?

3 个答案:

答案 0 :(得分:3)

你无法使用这样的对象,你必须做这样的事情;

 var width = height = 280; // store values
 var option = jQuery.extend({
        parent: this,
        width:  width,
        height: height

        circle: {
            x:          (width / 2) + 5,   // option doesn't exist
            y:          (height / 2) + 22, // option doesn't exist
            radius:     70,
            speed:      5,
            rotation:   0,
            angleStart: 270,
            angleEnd:   90,
            hue:        220,
            thickness:  15,
            blur:       20
        }
    }, options);
 // option is now created and exists here

你可以做这样的事情

var tempOption = {
    parent: this,
    width:  280,
    height: 280
};


tempOption.circle = {
    x:          (tempOption.width / 2) + 5,   // option doesn't exist
    y:          (tempOption.height / 2) + 22, // option doesn't exist
    speed:      5,
    rotation:   0,
    angleStart: 270,
    angleEnd:   90,
    hue:        220,
    thickness:  15,
    blur:       20
};


var option = jQuery.extend(tempOption, options);

答案 1 :(得分:1)

x: (option.width / 2) + 5,运行时,option尚不存在,因此您无法访问option.width

就这样做:

var width = 280;
var height = 280;
var option = jQuery.extend({
    parent: this,
    width:  width,
    height: height,

    circle: {
        x:          width / 2 + 5,
        y:          height / 2 + 22,
        radius:     70,
        speed:      5,
        rotation:   0,
        angleStart: 270,
        angleEnd:   90,
        hue:        220,
        thickness:  15,
        blur:       20
    }
}, options);

答案 2 :(得分:0)

对象文字中

option.widthoption.height不可用;将依赖项提取到对象中并合并所有:

var parent = {}; //set your parent here
var width = 10;
var height = 20;

var option = jQuery.extend({ width: width, height: height, parent: parent },{
        circle: {
            x:          (width / 2) + 5,
            y:          (height / 2) + 22,
            radius:     70,
            speed:      5,
            rotation:   0,
            angleStart: 270,
            angleEnd:   90,
            hue:        220,
            thickness:  15,
            blur:       20
        }
    }, options);