2016-11-08 49 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();