简体   繁体   English

对JavaScript中的原型感到困惑

[英]Confused about prototype in javascript

var y=function(){
    return new y.prototype.greeting();
}
y.prototype={
    greeting:function(){
        alert("hello world");
    }
}

new y();

the above code will alert("hello world"); 上面的代码将发出警报(“ hello world”);

but if I remove the .prototype and change that line to return new y.greeting(); 但是如果我删除.prototype并更改该行以return new y.greeting();

an error will be occurred: 将会发生错误:

undefined is not a function 未定义不是函数

var y=function(){
    return new y.greeting();
}
y.prototype={
    greeting:function(){
        alert("hello world");
    }
}

new y();

why I can't call the greeting method without prototype here? 为什么我不能在没有prototype情况下调用greeting方法?

thanks a lot 非常感谢

y is a function, the [[Prototype]] of which is Function - so when you ask the interpreter to look up y.greeting for you, it first looks at y itself, then it checks Function.prototype and then it checks Object.prototype . y是一个函数,其中的[[Prototype]]Function因此,当您要求解释器查询y.greeting时,它首先查看y本身,然后检查Function.prototype ,然后检查Object.prototype

When you create a new y then the prototype property of y will be set on the object that is created. 创建 new yy将在创建的对象上设置new yprototype属性。 So if you did new (new y()).greetings() then you would get your alert . 因此,如果您执行new (new y()).greetings() ,则将收到alert

Another way to think about it is the prototype property of a constructor function is the prototype of any child objects that will be created by calling new constructor . 另一种考虑方式是构造函数的prototype属性是将通过调用new constructor创建的任何子对象的prototype The actual internal [[Prototype]] of the constructor will always be based on whatever constructed it . 构造函数的实际内部[[Prototype]]将始终基于构造函数的任何内容

You can see this in the example I put together below. 您可以在下面的示例中看到这一点。 Object.getPrototypeOf will return the internal [[Prototype]] property, so we can see what is actually going on: Object.getPrototypeOf将返回内部的[[Prototype]]属性,因此我们可以看到实际发生的情况:

> var test = function() {}
> Object.getPrototypeOf(test)
function Empty() {}

// Setting the prototype property
// does not change the [[Prototype]] of test
> test.prototype = {x: 1}
> Object.getPrototypeOf(test)
function Empty() {}

// But it *does* change the prototype of
// objects *created by* test.
> var x = new test
> Object.getPrototypeOf(x)
Object {x: 1}

return new y.greeting(); tries to access an attribute (function) of y which doesn't really exist. 尝试访问y真正不存在的属性(函数)。 That's why it throws the error 'undefined is not a function' because, the attribute of y contains a variable which contains a function. 这就是为什么它会引发错误“未定义的不是函数”的原因,因为y的属性包含一个包含函数的变量。 It's like three floors, where you cannot go to ground floor from the second floor without going to first floor; 就像三层楼一样,您不能从二楼到一楼而不要一楼。 kind of hierarchy. 一种等级制度。 Got it? 得到它了?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM