在构造函数内外为 prototype 属性赋值的区别

2015-04-18 20:43:08 +08:00
 coolzjy

function Person(){
    Person.prototype.talk=function(){alert("saying")};
}

function Men(){
}

Men.prototype = new Person();

var men = new Men();
men.talk();

可以执行成功,但

function Person(){
    Person.prototype.talk=function(){alert("saying")};
}

function Men(){
    Men.prototype = new Person();
}   

var men = new Men();
men.talk();

报错。请问在构造函数内部和外部为 prototype 赋值有何区别

2733 次点击
所在节点    JavaScript
4 条回复
iyangyuan
2015-04-18 21:14:11 +08:00
因为第二个在new的时候,你还没有指定原型。

new相当于创建一个新对象,然后把这个新对象的原型指向函数(类)的prototype对象,第二个在构造方法里才指定原型,此时新对象的创建已经完成,它早已指向别处,所以报错。

在第二个例子中,如果再new一次,应该就不会报错了。
bombless
2015-04-18 23:15:21 +08:00
function Men(){
function ret() {}
ret.prototype = new Person();
ret = new ret;
Men = ret;
return ret
}
作弊可以吗,哈哈哈
xavierchow
2015-04-18 23:43:49 +08:00
请看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
```
When the code new foo(...) is executed, the following things happen:

1. A new object is created, inheriting from foo.prototype.
2.The constructor function foo is called with the specified arguments and this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments.
3.The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
```
第一步的时候,Men的prototype还不是Person对象,第二步才是执行constructor,而在你的代码中这时才改Men的prototype, 晚了。
xavierchow
2015-04-19 11:36:20 +08:00
补充一点,对象初始化之后prototype是不可以改变,但是可以修改prototype的属性。
所以new之后再assign prototype是不行的,但是(new Person()).talk()是OK的。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/184613

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX