繁体   English   中英

对JavaScript中的原型感到困惑

[英]Confused about prototype in javascript

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

new y();

上面的代码将发出警报(“ hello world”);

但是如果我删除.prototype并更改该行以return new y.greeting();

将会发生错误:

未定义不是函数

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

new y();

为什么我不能在没有prototype情况下调用greeting方法?

非常感谢

y是一个函数,其中的[[Prototype]]Function因此,当您要求解释器查询y.greeting时,它首先查看y本身,然后检查Function.prototype ,然后检查Object.prototype

创建 new yy将在创建的对象上设置new yprototype属性。 因此,如果您执行new (new y()).greetings() ,则将收到alert

另一种考虑方式是构造函数的prototype属性是将通过调用new constructor创建的任何子对象的prototype 构造函数的实际内部[[Prototype]]将始终基于构造函数的任何内容

您可以在下面的示例中看到这一点。 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(); 尝试访问y真正不存在的属性(函数)。 这就是为什么它会引发错误“未定义的不是函数”的原因,因为y的属性包含一个包含函数的变量。 就像三层楼一样,您不能从二楼到一楼而不要一楼。 一种等级制度。 得到它了?

暂无
暂无

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

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