2016-09-27 76 views
0

我一直在尋找最佳解決方案,但我真的不知道我應該找什麼關鍵字。我需要一點點的我問題的解釋:)那是我的代碼:Javascript object/function accesibility inside another

function fluidEdge(params) { 
    var fluid = {}; 
    fluid.point = function(config){ 
    fluid.x = config.x; 
    fluid.y = config.y; 
    }; 
    fluid.renderShape = function(params){ 
    params = params || {}; 
     var x = params.x || 0; 
     var y = params.y || 0; 
    point = new fluid.point({ 
     x: x, 
     y: y 
    }); 
    console.log(point.x); 
    }; 

    return fluid; 
} 

var test = new fluidEdge({}); 

test.renderShape({x: 50, y: 100}); 

Fiddle

我的例子要複雜得多,所以我真的不能重建代碼,我已經儘可能簡化它盡我所能。我想在fluid.renderShape內訪問fluid.point函數。我不知道我該怎麼做,我嘗試了幾種方法。

之前,我沒有使用var fluid = {};fluid.,但this.和一切工作正常。

如果我犯了什麼錯誤,你也可以指出。提前致謝。

+0

你的代碼很混亂。什麼是'var fluid = {};'for? – passion

回答

1

您似乎與構造函數和函數的工作方式略有混淆。您的代碼或許應該看起來有點像這樣:

function FluidEdge(params) {} 

FluidEdge.Point = function(config) { 
    this.x = config.x; 
    this.y = config.y; 
} 

FluidEdge.prototype.renderShape = function(params) { 
    params = params || {}; 
    var x = params.x || 0; 
    var y = params.y || 0; 

    var point = new FluidEdge.Point({x: x, y: y}); 

    console.log(point.x); 
} 

var test = new FluidEdge({}); 
test.renderShape({x: 50, y: 100}); 

注意使用prototype表示的構造方法,以及使用this來引用構造的對象。

另請注意,將構造函數放在實例變量上通常是一個糟糕的主意,除非您知道自己在做什麼並且有很好的理由。

值得注意的是,代碼變得更好看,如果你把ES2015的優勢特點

class FluideEdge { 
    renderShape({x = 0, y = 0}) { 
    var point = new FluidEdge.Point({x, y}); 
    console.log(point.x); 
    } 
} 
FluidEdge.Point = class { 
    constructor({x, y}) { 
    this.x = x; 
    this.y = y; 
    } 
} 
+0

它的工作原理,但我仍然認爲嵌套代碼更乾淨。在第一次函數聲明之後每次使用prototype都有點難看。我從http://checkman.io/blog/creating-a-javascript-library/取得了我的想法。我喜歡ES2015的方式tbh :) – RaV

+0

這很好,但他們沒有使用構造函數('new'關鍵字)。你不應該混淆你的條款;) –

0

我才意識到,我只是改變了太多thisfluid在我的代碼。問題出在那裏:

fluid.point = function(config){ 
    this.x = config.x; 
    this.y = config.y; 
}; 

它在這個小小的改變之後運作良好。