2016-11-08 52 views
0

我正在做一個Javascript課程的介紹,需要一些最佳實踐和一些總體反饋的幫助,因爲我的老師似乎對自從他任職以來幫助我們的學生不感興趣。Object.create和init

完整免責聲明:代碼在編譯下,並且是正確(從教授提供的測試用例中判斷)。因此,我不需要實際任務的幫助,但是如何解釋與運行背後的create()和任何(如果有的話)邏輯捆綁在一起的init的用例。

/** 
* Exercise 2.2 
* 
* Create a method 'shape.init(x, y, height, width)' that helps you to 
* initiate a object. Try it out by re-initing 'shape1' using the method. 
* 
* Answer with 'shape1.print()'. 
* 
* Write your code below and put the answer into the variable ANSWER. 
*/ 

function shape(){ 
    this.x = 0; 
    this.y = 0; 
    this.height = 0; 
    this.width = 0; 
} 

shape.print = function(){ 
    return 'x:' + this.x + ', ' + 
     'y:' + this.y + ', ' + 
     'height:' + this.height + ', ' + 
     'width:' + this.width; 
} 

var shape1 = Object.create(shape, {x : {value : 29}, 
            y : {value : 56}, 
            height : {value : 17}, 
            width : {value : 19}}); 


shape.init = function(x, y, height, widht){ 
    function shape(x, y, height, width){ 
    this.x = x; 
    this.y = y; 
    this.height = height; 
    this.width = width; 
    } 
} 

shape1.init(29, 56, 17, 19); 


ANSWER = shape1.print(); 

我有困難的時候,下面是你爲什麼會需要的時候可以使用的Object.create一個初始化函數()(這在我的心靈的作品一樣的INIT)...

老師在這一點上只是一無所知,或者是否存在這樣的情況:實現已經使用object.create()初始化對象的init是否值得呢?

+0

我認爲你需要更具體一點。我不確定哪些位需要澄清。部分原因可能是因爲這不像JS成語。 – ssube

+0

那麼,我不確定的是,爲什麼我們在任何情況下都需要一個init,我們基本上使用object.create()。對我而言,他們是獨一無二的;一個初始化老派對象(java中的'classes'),另一個通過對已經定義的對象的引用來初始化對象,並且它的屬性... – geostocker

+2

'init'函數似乎不正確。它不會返回任何東西。 –

回答

0

(這個答案大多是試圖跟隨運動,而不是什麼是 「正確」 或標準JavaScript公約的精神。)

答案是最有可能將它包裝成一個功能:

shape.init = function(x, y, height, width) { 
    return Object.create(shape, {x : {value : x}, 
            y : {value : y}, 
            height : {value : height}, 
            width : {value : width}}); 
}; 

shape1 = shape.init(29, 56, 17, 19); // now creating a shape is simply 1 function call 

ANSWER = shape1.print(); 
+0

工程就像一個魅力。你介意添加一個補充,爲什麼它不被認爲是好的做法? :) – geostocker

+0

@geostocker還有其他的來源可以解釋它比我好。 OOP的標準方法是創建類類功能。像https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Custom_objects。 – tcooc

+0

那麼,基本的構造函數呢。那麼,我不會花太多精力去理解教授關於這項任務的思維過程。 我相信你可以看到我的困惑。我幾乎獲得了東南大學的學位,並認爲我會選擇這門課程來獲得額外的學分。沒意識到它會變得如此混亂......:p – geostocker

0

1.不要使用Object.create。 看起來要好得多:

shape1= new shape(args); 
//this just works together with the thing guest answered 

1B。是的您選擇權,初始化沒有道理,它會如果生成自定義對象:

shape={}; 
shape.init=function(args){ 
return {}; 
} 
shape1=shape.init(args); 
  • 使用原型,因爲它更好地爲內存消耗:

    形狀.prototype.print =函數(){}

  • 0

    使用OR||,其屬性設置。不確定shape1,shape.initObject.create()是什麼目的?

    function Shape(x, y, height, width){ 
        this.x = x || 0; 
        this.y = y || 0; 
        this.height = height || 0; 
        this.width = width || 0; 
    } 
    
    var shape1 = new Shape(29, 56, 17, 19); 
    var shape2 = new Shape(1, 2, 3, 4); 
    var shape3 = new Shape();