博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
js--constructor prototype
阅读量:6034 次
发布时间:2019-06-20

本文共 1951 字,大约阅读时间需要 6 分钟。

hot3.png

var someObj = function() {
} var p = new someObj(); alert(someObj.prototype); // This works alert(p.prototype); // UNDEFINED, but why? someObj.prototype.model= "Nissan"; alert(p.model); // This works! I understand the dynamic nature of prototypes, but doesn't that mean that p.prototype === someObj.prototype?
一道来自stackoverflow的问题:
 

That's because prototype is a property of the constructor function, not a property of itself. However, theprototype object has a reference to the constructor, so you can access an object's prototype via itsconstructor property:

function Foo() {} Foo.prototype.foo = "bar"; var c = new Foo; console.log( c.constructor === Foo ); // true console.log( c.constructor.prototype ); // { foo: 'bar' }

However, this will not work if you overwrite the initial prototype property of the constructor function:

function Foo() {} // I overwrite the prototype property, so I lose the initial reference // to the constructor. Foo.prototype = {
foo: "bar" }; var c = new Foo; console.log( c.constructor === Foo ); // false console.log( c.constructor === Object ); // true console.log( c.constructor.prototype ); // {}

That's why you're better off using the new  method introduced in ES5.

function Foo() {} Foo.prototype = {
foo: "bar" }; var c = new Foo; console.log( c.constructor === Foo ); // false console.log( c.constructor === Object ); // true console.log( c.constructor.prototype ); // {} console.log( Object.getPrototypeOf(c) ); // { foo: 'bar' }

Another solution would have been to make sure you restore the constructor reference on the prototype:

function Foo() {} // Overwriting the initial prototype  Foo.prototype = {
constructor: Foo, // restore the constructor reference foo: "bar" };
 
prototype是作为constructor的一个属性,上面提到如果把prototype覆盖,那么就找不到原先的constructor. 另外,对于这个问题,我们在定义函数的时候,函数定义的时候函数本身就会默认有一个prototype的属性,而我们如果用new 运算符来生成一个对象的时候就没有prototype属性,可以这么理解.

转载于:https://my.oschina.net/lgmcolin/blog/102314

你可能感兴趣的文章
研磨设计模式 之 装饰模式(Decorator)2
查看>>
模块化编程
查看>>
怎样组建流程优化组织
查看>>
JAVA操作properties文件
查看>>
find 命令
查看>>
ubuntu 12.10 virtualenv & django
查看>>
点击复选框添加或删除value值到input输入框中
查看>>
安装Apache
查看>>
cacti导入Linux主机模板 Windows主机模板
查看>>
python 的SimpleXMLRPCServer,xmlrpclib
查看>>
Redis-主从复制
查看>>
阿里云为何成众矢之的?
查看>>
我的友情链接
查看>>
LAMP架构讲解(续一)
查看>>
我的友情链接
查看>>
笔记本出厂预装Win8改装Win7的操作步骤及常见问题
查看>>
我的友情链接
查看>>
DHCP Snooping + Dynamic ARP Inspection配置
查看>>
Bacula 7.0.2 发布,备份管理系统
查看>>
asterisk RTP透传相关参数整理
查看>>