Object.create和init

时间:2016-11-08 18:42:19

标签: javascript

我正在介绍Javascript课程,并需要一些最佳实践和一些整体反馈的帮助,因为我的老师似乎对帮助我们的学生不感兴趣,因为他有任期。

完全免责声明:下面的代码编译并正确(根据教授提供的测试用例判断)。所以我不需要实际分配的帮助,但是如何解释与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();

我遇到困难的原因是为什么你需要一个init-function,当你可以使用object.create()时(在我看来它和init一样)......

教师此时是否只是无知,或者是否存在实现init的情况,你已经在使用object.create()初始化对象真的值得吗?

3 个答案:

答案 0 :(得分:0)

1.不要使用Object.create。 new 看起来好多了:

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

1b中。你是对的,init没有意义,如果你生成自定义对象,那就是:

shape={};
shape.init=function(args){
return {};
}
shape1=shape.init(args);
  1. 使用原型设计,因为它更适合内存消耗:

    shape.prototype.print =函数(){ }

答案 1 :(得分: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();

答案 2 :(得分:0)

使用OR ||设置属性。不确定shape1shape.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();
相关问题