Javascript`new`运算符&原型 [英] Javascript `new` operator & prototype
问题描述
假设我们创建一个名为'Shape'的函数,并添加一个属性'name'&方法'toString'在它的原型:
Say we create a Function named 'Shape', and add a property 'name' & method 'toString' on it's prototype:
var Shape = function () {};
Shape.prototype.name = 'Shape';
Shape.prototype.toString = function () {
return this.name;
}
console.log(Shape.name); // ''
console.log(Shape.toString()); // function () {}
var Triangle = new Shape();
console.log(Triangle.name); // 'Shape'
console.log(Triangle.toString()); // 'Shape'
'NEW'操作符做了两件事:
这个到'Triangle'
2.它将三角形的[[proto]]指向Shape.prototype
'NEW' operator did two things: 1. It points this to 'Triangle' 2. It points 'Triangle's [[proto]] to Shape.prototype
然后我可以理解当我调用name& toString on Triangle,它搜索它的原型链,直到Shape.prototype。
Then I can understand when I call name & toString on Triangle, it searches for it's prototype chain till Shape.prototype.
但是我的问题是为什么不是Shape搜索它的属性&属性?
But my problem is why not Shape searching for it's property(even it's an Object) for the method & property?
感谢。
推荐答案
我知道。
这里 Shape
是一个函数&一个函数只是一种特殊类型的对象,和任何对象一样,一个函数可以有属性。
Here Shape
is a function & A function is just a special kind of object, and like any object a function can have properties.
函数自动获得一个名为 code>,这只是一个空对象。
Functions automatically get a property called prototype
, which is just an empty object. This object gets some special treatment.
当你做新 c> Function
所创建的对象将继承其构造函数原型的所有属性。
When you will do a new
of a Function
the created object inherits all of the properties of its constructor’s prototype.
喜欢下面
var Shape = function () {};
Shape.prototype.name = 'Shape';
Shape.prototype.toString = function () {
return this.name;
}
当你说
var Triangle = new Shape();
所以它做什么
var Triangle = {};
Triangle.name = Shape.prototype.name
Triangle.toString = Shape.prototype.toString;
它设置对象 Triangle
to delegate to Shape.prototype。
"it sets up the object Triangle
to delegate to Shape.prototype."
所以当你做
Triangle.name //Shape
Triangle.toString() // Shape
但是 Shape
你必须说
Shape.prototype.name //Shape
Shape.prototype.toString() //Shape
这篇关于Javascript`new`运算符&原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!