2014-01-14 36 views
3

爲什麼它不起作用?無法在JSON中讀取父級的知識產權

我收到此錯誤信息:

TypeError: Cannot read property 'width' of undefined

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); 

我怎麼能看 「父母」 的財產?
我應該使用另一個前綴嗎?

+2

因爲在對象完全創建之前無法讀取對象的屬性。 – Blazemonger

回答

4

你不能像這樣的對象工作,你必須做這樣的事情;

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); 
+0

謝謝你,它的工作原理。問題是現在我必須檢查用戶是否指定了'width'和'height',如果沒有,則設置默認值。 – guest459473

+0

嘗試更新位。 – iConnor

2

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); 
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);