Discuss / JavaScript / 换一种方法

换一种方法

Topic source

lmtooT_T

#1 Created at ... [Delete] [Delete and Lock User]
        function Person(name,age){
            this.name = name;
            this.age = age;
        }
        function Student(name,age,className){
            Person.call(this,name,age);
            this.className = className;
        }

        Student.prototype.constructor.prototype=Person.prototype

        var stu = new Student('jason',24,'Grade 2');
        console.log(stu.name);//jason
        console.log(stu.age);//24
        console.log(stu.className);//Grade 2
        console.log(stu instanceof Student);//true
        console.log(stu instanceof Person);//true

这么搞好像也可以

木落绕指

#2 Created at ... [Delete] [Delete and Lock User]

**stu.constructor应该指向的是Student函数吧,毕竟stu是由Student生成的。

来自初学者的理解。 你代码中的

Student.prototype.constructor.prototype=Person.prototype

相当于

Student.prototype=Person.prototype

因为

Object.prototype.constructor===Object//true

导致Student和Person共享了原型对象

var lucy = new Person('lucy',13);
lucy instanceof Student;//true应该为false

如果为Student的原型对象增加一个方法

Student.prototype.intro=function(){return "I am a Student";}
lucy.intro()//"I am a Student"

解决办法为改成

function Person(name,age){
            this.name = name;
            this.age = age;
        }
        function Student(name,age,className){
            Person.call(this,name,age);
            this.className = className;
        }
Student.prototype = Object.create(Person.prototype);//修改后

var p = new Person('lucy',22);
var s = new Student('tom',12,'grade1');
p instanceof Student;//false
s instanceof Person;//true
Student.prototype.intro=function(){return 'I am a student'};
p.intro()//报错
s.intro()//"I am a student"
忘加了句Student.prototype.constructor=Student

  • 1

Reply