本文介绍了JavaScript构造函数不会被执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现一个我在JavaScript继承中找到的例子,子对象似乎没有按预期构造。在下面的示例中,创建jill实例不返回Jill对象,并且无法调用来自子代或父代的方法。

I'm attempting to implement an example I found on JavaScript inheritance, and the child object does not seem to be constructing as expected. In the example below, creating the jill instance does not return a Jill object and the methods from the child or parent cannot be called.

var Person = function() {
  this.name = "unnamed";
}
Person.prototype.sayName = function() {
  console.log("My name is " + this.name);
}
var Jill = function() {
  var jill = function() {
    Person.call(this);
    this.name = "Jill";
  };
  jill.prototype = Object.create(Person.prototype);
  jill.prototype.constructor = jill;
  jill.prototype.expressJoy = function() {
    console.log("Huray!");
  };
  return jill;
}
var jill = new Jill();
console.log(jill instanceof Jill); // false
jill.expressJoy(); // error, is not a function
jill.sayName(); // error, seen if comment out previous line


推荐答案

你case var Jill 像一个常规函数,不像构造函数。

更改您的代码如下所示:

In you case var Jill acts like a regular function, not like constructor.
Change your code as shown below:

var Jill = (function () {
    function Jill() {
        Person.call(this);
        this.name = "Jill";
    };
    Jill.prototype = Object.create(Person.prototype);
    Jill.prototype.constructor = Jill;
    Jill.prototype.expressJoy = function () {
        console.log("Huray!");
    };
    return Jill;
})();

var jill = new Jill();
console.log(jill);   // Jill {name: "Jill"}
console.log(jill instanceof Jill); // true
jill.expressJoy(); // Huray!
jill.sayName();    // My name is Jill

现在 Jill 是一个真正的构造函数,将按您的预期生成对象。 (BTW,构造函数名称应该以大写字母开头,根据良好做法)

Now Jill is a "real" constructor that will generate objects as you expected. (BTW, A constructor name should start with an uppercase letter, according to good practice)

这篇关于JavaScript构造函数不会被执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 05:11