【问题标题】:Javascript prototype handling self and constructor parameters处理自我和构造函数参数的Javascript原型
【发布时间】:2014-09-29 16:54:47
【问题描述】:

我试图了解 javascript 原型设计原理,但无法让一些基本的东西发挥作用。 我试图实现的一件事是,创建一个基础对象,它处理构造函数输入,并根据该输入设置值,如果没有给出构造函数参数,则设置默认值。

另外,我不知道如何将 this 存储在一个变量中,以便它指向正确的对象实例(可能是父对象)

以下是我尝试创建基本继承的 2 个版本。 (我以前见过的第一个,但它不允许我使用其基对象的构造函数处理传递给扩展对象的构造函数参数。 第二个版本...是我想出的启用它的东西,但是...我从未见过有人使用这样的原型,并且我确定它是错误的方式(因为原型属性是一个函数而不是一个对象)

解决这两个问题的正确方法是什么。

var Person = function(conf) {
    if (!conf) {conf = {};}
    var _person = this;
    this.first_name = conf.first_name;
    this.last_name = conf.last_name;
    this.greet = function() {
        alert("Hi, im " + this.first_name + " " + this.last_name );
    }
    this.callback_greet = function() {
        alert("Hi, im " + _person.first_name + " " + _person.last_name );
        console.log("this:", this, " _person:", _person );
    }
}

var Student = function(conf) {
    if (!conf) {conf = {};}
    /* id like to pass this conf on to Person constructor */
    this.report = function() {
        alert(  this.first_name + " " + this.last_name + " is ready to study"  );
    }
}
Student.prototype = new Person();

var Teacher = function(conf) {
    if (!conf) {conf = {};}
    this.teach = function() {
        alert(  this.first_name + " " + this.last_name + " is ready to teach...maggots"  );
    }
}
Teacher.prototype = new Person();

student  = new Student({first_name: "Mike", last_name: "Stud"});
//student.first_name="Mike";
//student.last_name="Stud";
student.greet();
/* alerts Hi, im Mike Stud */


teacher  = new Teacher();
teacher.first_name="John";
teacher.last_name="Smith";
teacher.teach();
/* alerts John Smith is ready to teach...maggots */
teacher.callback_greet ();
/* both alerted values are undefined */

//_________________________
//_______Version 2  _______
//_________________________

var Person = function(conf) {
    if (!conf) {conf = {};}
    var _person = this;
    this.first_name = conf.first_name;
    this.last_name = conf.last_name;
    this.greet = function() {
        alert("Hi, im " + this.first_name + " " + this.last_name );
    }
    this.callback_greet = function() {
        alert("Hi, im " + _person.first_name + " " + _person.last_name );
        console.log("this:", this, " _person:", _person );
    }
}

var Student = function(conf) {
    if (!conf) {conf = {};}
    this.prototype = Person;
    this.prototype(conf);
    this.report = function() {
        alert(  this.first_name + " " + this.last_name + " is ready to study"  );
    }
}

var Teacher = function(conf) {
    if (!conf) {conf = {};}
    this.prototype = Person;
    this.prototype(conf);
    this.teach = function() {
        alert(  this.first_name + " " + this.last_name + " is ready to teach...maggots"  );
    }
}

var Principal = function(conf) {
    if (!conf) {conf = {};}
    this.prototype = Teacher;
    this.prototype(conf);
    this.dicipline_teachers = function() {
        alert(  this.first_name + " " + this.last_name + " thy all mighty principal is watching you"  );
    }
}

student  = new Student({first_name: "Mike", last_name: "Stud"});
student.greet();
/* alerts Hi, im Mike Stud */

teacher  = new Teacher({first_name: "John", last_name: "Smith"});
teacher.teach();
/* alerts John Smith is ready to teach...maggots */

principal  = new Principal({first_name: "David", last_name: "Faustino"});
principal.teach();/* alerts David Faustino is ready to teach...maggots */
principal.dicipline_teachers();/* David Faustino thy all mighty principal is watching you*/

【问题讨论】:

    标签: javascript inheritance prototype


    【解决方案1】:

    嗯,你的第二个版本实际上……有点……正确

    你的sn-p是什么

    var Student = function(conf) {
        this.prototype = Person;
        this.prototype(conf);
    

    在这里做:

    1. 使用new Student() 调用时,有一个Student 实例为this
    2. 在包含函数(在本例中为父构造函数)的实例上创建一个属性,这实际上是在实例上创建一个方法
    3. 将其作为方法调用。这意味着,调用 Person 函数时,它的 this 指向我们在此处拥有的实例 - 然后 Person 在该实例上进行设置。

    这正是我们想要的。也许除了创建不必要的属性。请注意,该属性的名称为 prototype 与其功能完全无关,您也可以使用 myParentConstructor 或其他名称。

    在标准的 JavaScript 继承中,我们执行与该方法调用类似的事情 - 我们希望在当前(子)实例上调用父构造函数 on 以便设置它。但是,我们为此使用.call() method


    现在我们也想使用原型。在您的代码中,所有方法greetreportteachdicipline_teachers 可以在实例之间共享,因此它们可以-and should-继续ConstructorFn.prototype。为了让所有的老师、学生、校长都继承这些方法,我们需要建立一个原型链(继承层次结构)。我们don't want to use new Person 因为它会调用构造函数并在原型对象上设置first_name 之类的东西来共享它们——但我们不希望这样。相反,我们使用Object.create

    总而言之,您的代码将如下所示:

    function Person(conf) {
        if (!conf) {conf = {};}
        var _person = this;
        this.first_name = conf.first_name;
        this.last_name = conf.last_name;
        this.callback_greet = function() {
            alert("Hi, im " + _person.first_name + " " + _person.last_name );
            console.log("this:", this, " _person:", _person );
        };
    }
    Person.prototype.greet = function() {
        alert("Hi, im " + this.first_name + " " + this.last_name );
    };
    
    function Student(conf) {
        Person.call(this, conf);
    }
    Student.prototype = Object.create(Person.prototype, {constructor:{value:Student}});
    Student.prototype.report = function() {
        alert(  this.first_name + " " + this.last_name + " is ready to study"  );
    };
    
    function Teacher(conf) {
        Person.call(this, conf);
    }
    Teacher.prototype = Object.create(Person.prototype, {constructor:{value:Teacher}});
    Teacher.prototype.teach = function() {
        alert(  this.first_name + " " + this.last_name + " is ready to teach...maggots"  );
    };
    
    function Principal(conf) {
        Teacher.call(this, conf);
    }
    Principal.prototype = Object.create(Teacher.prototype, {constructor:{value:Principal}});
    Principal.prototype.dicipline_teachers = function() {
        alert(  this.first_name + " " + this.last_name + " thy all mighty principal is watching you"  );
    };
    

    【讨论】:

      【解决方案2】:

      (1) 最好在对传递的值的类型进行适当的健全性检查后处理设置默认值:

      var Constr = function (conf) {
        if (!!conf && !(conf instanceof Object)) {
          throw new Error('An invalid parameter was passed to Constr.');
        }
        if (!conf) { // Prevent "Can't read property 'name' of undefined." 
          conf = {};
        }
        this.name = conf.name || null; // Set defaults this way.
      };
      

      (2) 您需要使用 Object.create()Object.apply() 来解决这个问题:

      var Person = function (param1, param2) {
        this.param1 = param1;
        this.param2 = param2;
      }
      
      Person.prototype.cough = function () {
        // Do stuff.
      }
      
      var Student = function (param1, param2, paramN) {
        Person.call(this, param1, param2);
        this.paramN = paramN; // Define a new property on the subclass
      }
      
      // Invoke the superclass to have the subclass inherit properties and methods.
      Student.prototype = Object.create(Person.prototype);
      Student.prototype.constructor = Student;
      

      【讨论】:

        猜你喜欢
        • 2014-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-07
        • 1970-01-01
        • 2017-08-21
        • 2015-04-20
        • 2010-12-05
        • 2017-06-12
        相关资源
        最近更新 更多