码迷,mamicode.com
首页 > 编程语言 > 详细

为什么要设置Javascript对象prototype的constructor

时间:2014-06-28 18:51:34      阅读:299      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   color      

最近读了一篇关于Javascript面向对象编程的文章,里面介绍了Javascript中的类,对象,属性,方法,构造函数,继承,封装,抽象和多态性。读完之后感觉受益匪浅,对Javascript有了进一步的认识。文章的地址在这里

在讲到继承的时候,文章里面用了如下的例子

// define the Person Class
function Person() {}

Person.prototype.walk = function(){
  alert (‘I am walking!‘);
};
Person.prototype.sayHello = function(){
  alert (‘hello‘);
};

// define the Student class
function Student() {
  // Call the parent constructor
  Person.call(this);
};

// inherit Person
Student.prototype = new Person();

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
 
// replace the sayHello method
Student.prototype.sayHello = function(){
  alert(‘hi, I am a student‘);
};

// add sayGoodBye method
Student.prototype.sayGoodBye = function(){
  alert(‘goodBye‘);
};

var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();

// check inheritance
alert(student1 instanceof Person); // true 
alert(student1 instanceof Student); // true

里面的这行代码,让我困惑了:

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;

因为加不加这行代码,最后的运行结果都不受到影响,所以不理解加上去有什么作用。网上搜索了一下,在Stack Overflow网站中找到了一个类似的提问

原文地址如下

http://stackoverflow.com/questions/8453887/why-is-it-necessary-to-set-the-prototype-constructor

提问者问到那行代码是否有特殊作用,是否可以省略?回答者给出了下面的例子作解答:

// define the Person Class  
function Person(name) {
    this.name = name;
}  

Person.prototype.copy = function() {  
    // return new Person(this.name); // just as bad
    return new this.constructor(this.name);
};  

// define the Student class  
function Student(name) {  
    this.name = name; 
}  

// inherit Person  
Student.prototype = new Person();  

var student1 = new Student("trinth");  
console.log(student1.copy() instanceof Student); // => false

这个例子中,省去了那行设置prototype中constructor的代码,可以看到最后一行student1.copy() instanceof Student得到的结果是false,并不是我们想要的。加上那行代码之后,student1.copy() instanceof Student得到的结果是true,这个才是我们想要的。

所以,设置子类中prototype的constructor还是有必要的。

为什么要设置Javascript对象prototype的constructor,布布扣,bubuko.com

为什么要设置Javascript对象prototype的constructor

标签:style   blog   http   java   color      

原文地址:http://www.cnblogs.com/liangzi4000/p/3797159.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!