JavaScript原型和构造函数

时间:2015-05-31 22:26:08

标签: javascript

我有以下代码用于学习JavaScript。

function Pizza(type, slices) {
    this.type = type;
    this.slices = slices;
}


Pizza.prototype.divvyUp = function () {
    alert("The " + this.type + " pizza has been divvied up!");
};

var sausagePizza = new Pizza("sausage", 8);


sausagePizza.constructor.prototype.divvyUp();
sausagePizza.divvyUp();
if (sausagePizza.constructor.prototype.divvyUp === sausagePizza.divvyUp)
{
    alert("yes they are equal");
}

当执行这两行代码时,事情是这样的:

sausagePizza.constructor.prototype.divvyUp();
sausagePizza.divvyUp();

虽然他们旁边的if声明批准他们的类型和价值相同但他们是平等的。但是第一行给了我一个结果,其内容如下所示“未定义的披萨已经被分开了”,第二行结果是给了我一个不同的结果,上面写着“香肠披萨已被分开”。我非常困惑的是,为什么不能在这两个读this.type变量值中排在第一行,并根据if语句在divvyUp()函数内的警报消息中抛出一个未定义的值。

1 个答案:

答案 0 :(得分:2)

两者之间的区别在于如何在函数调用中绑定“this”。

左边的对象。函数调用前面是“this”绑定的对象。

sausagePizza.constructor.prototype.divvyUp();
//sausagePizza.constructor.prototype is left of the .divvyUp()
//so it is bound to this. However, the prototype object does not have
//a type property so it this.type returns undefined

但是,对于sausagePizza的情况,构造函数确实创建了这些属性。

sausagePizza.divvyUp()
//here sausage pizza is to left of .dizzyUp() and "this" is bound to it.

编辑: 要在Javascript中理解原型,可能有助于完成所有内容的拼写。 First Functions是对象,这意味着它们具有属性。每个函数都是使用一些基本属性创建的。其中一个是原型,它最初是一个空物体。

function Pizza(type, slices) {
  this.type = type;
  this.slices = slices;
}
console.log(Pizza.prototype) // prints {} an empty object

Pizza.prototype.divvyUp = function () {
  alert("The " + this.type + " pizza has been divvied up!");
};
console.log(Pizza.prototype) // prints {divvyUp: [Function]}

现在,当我们在函数前面使用new运算符时,它会创建一个新的空对象,设置对象__proto__和构造函数属性,然后运行带有“this”绑定的函数作为新对象。 / p>

var sausagePizza = new Pizza("sausage", 8);
console.log(sausagePizza) // {type: "sausage", slices: 8}
//Objects in javascript can have hidden properties. 
//If we unhide the relevant ones for this example
//sausagePizza really looks like this.

{
   constructor: Pizza, //the function
   __proto__: Pizza.prototype, //the object on the function
   type: "sausage",
   slices: 8
}

所以。操作符实际上是通过查看左侧的对象来查找右侧的键(例如)。如果它没有在左侧的属性对象中找到它正在查找的键,那么它会查看该对象的__proto__以获取该键。所以当你这样做时

sausagePizza.divvyUp()
//Javascript first looks into sausagePizza for divvyUp.
//It does not find it.
//then it looks for divvyUp in sausagePizza.__proto__
//it find divvyUp there and then () calls the function
//if javascript had not found divvyUp in sausagePizza.__proto__ then it would have
//looked into sausagePizza.__proto__.__proto__ if it existed, and so on