use*_*007 -1 javascript oop jquery
我正在尝试使用基于OOP的javascript/jQuery.我想将所有JS函数放在一个类中,因此可以轻松地重写/挂钩.
我尝试使用简单的OOP代码,但它给出了类型错误:不是构造函数.请查看我的代码并指导我的代码有什么问题,以及如何解决它.
var myTestClass = {
testAttribute : 'test', // atttribute
testMethod : function(){ alert( testAttribute); }
};
var my = new myTestClass();
my.testMethod();
Run Code Online (Sandbox Code Playgroud)
谢谢
查看提醒:
var myTestClass = {
testAttribute: 'test',
testMethod: function () { alert(this.testAttribute); }
};
myTestClass.testMethod();
Run Code Online (Sandbox Code Playgroud)
另一种方法:
function myTClass(){
var testAttribute = 'test';
this.testMethod = function () {
alert(testAttribute);
};
}
var obj = new myTClass();
obj.testMethod();
Run Code Online (Sandbox Code Playgroud)
延迟继承示例:
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;
Run Code Online (Sandbox Code Playgroud)