Object.create而不是object literal

时间:2017-10-22 21:21:05

标签: javascript object object-literal

我试图绕过这个Object.create thingybob。我现在无法找到它的用途。我的JS编码很早,但我很难掌握它的概念。对我而言,似乎过多地使代码复杂化了。有人可以向我解释一下,我是一个五岁的孩子吗?

我在这里阅读了这些文章: JavaScript inheritance: Object.create vs new

What is the 'new' keyword in JavaScript?

Understanding the difference between Object.create() and new SomeFunction()

Using "Object.create" instead of "new"

但它并没有为我做到这一点。如果我有这个代码,它看起来像Object.create,它怎么可能被调用?

$(document).ready(function () {
    var clicked = false;
    $("#john").click(function () {
        if (!clicked) {
            var johnImage = $("#john").clone(false);
            $("h2").html("John is in the box");
            $("h2").css({ 'color': 'red' });
            $("#johnbox").prepend(johnImage);
            clicked = true;
        }
    });
    $("#removejohn").click(function () {
        clicked = false;
        $("#john").remove();
        $("h2").html("Click John to put him in the Box");
        $("h2").css({ 'color': 'black' });
    });
});

1 个答案:

答案 0 :(得分:0)

Object.create()并非严格来说是JavaScript的必要部分。添加它是为了减少记住使用new的需要,并为我们提供了一种更明确的方法来创建从其他对象继承的实例。

我们来看看你的代码:

function Player (name, stopAtValue) {
  this.name = name
  this.stopAtValue = stopAtValue
}

// You have to remember to use "new" here, otherwise this binding won't work:
let player1 = new Player('John', 16);
console.log(player1.name, player1.stopAtValue);

// this binding fails when "new" is omitted
let player2 = Player('John', 16);
console.log(player2.name, player2.stopAtValue);

JavaScript开发人员应该从Pascal命名约定中知道函数是构造函数,并且应该使用new

但是,从根本上说,您的代码和Object.create()都可以让您获得相同的结果。只是Object.create()消除了对new的需求,并为您提供了一种非常明确的方式来表明您在做什么。

相关问题