TypeError:不是构造函数 [英] TypeError: not a constructor

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

问题描述

我正在尝试使用基于OOP的javascript / jQuery。我想将所有JS函数放在一个类中,因此可以轻松覆盖/挂钩。

I am trying to use OOP based javascript/jQuery. I want to put all my JS function inside a class, so it can be easily overridden/hooked.

我尝试使用简单的OOP代码,但它给出了类型错误:不是构造函数。
请查看我的代码并指导我的代码有什么问题,以及如何修复它。

I tried with a simple OOP code, but its giving type error: not a constructor. Please have a look at my code and guide me what is wrong in my code, and how to fix it.

var myTestClass = {
    testAttribute : 'test', // atttribute
    testMethod : function(){ alert( testAttribute); }
};

var my = new myTestClass();
my.testMethod();

谢谢

推荐答案

查看你的提醒:

var myTestClass = {
    testAttribute: 'test', 
    testMethod: function () { alert(this.testAttribute); }


  };


  myTestClass.testMethod();

另一种方法:

function myTClass(){
    var testAttribute = 'test';
    this.testMethod = function () {
      alert(testAttribute);
    };

  }

  var obj = new myTClass();
  obj.testMethod();

懒惰继承示例:

function myTClass(){

    this.testMethod = function () {
      alert(this.testAttribute);
    };

  }

  myTClass.prototype.testAttribute = 'test';

  var obj = new myTClass();
  obj.testMethod();

  function derivedTClass() {
    myTClass.call(this);
    this.testMethod = function () {
      alert('derived ' + this.testAttribute);
    };
  }

  derivedTClass.prototype = Object.create(myTClass.prototype);

  var obj2 = new derivedTClass();
  obj2.testMethod();

  derivedTClass.prototype.constructor = derivedTClass;

这篇关于TypeError:不是构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆