这是我第一次在Javascript中使用OOP概念。以前我在JQuery工作过。我已经定义了类似
的类function myContent() {
this.toUserID = "1234";
this.loadMainLabel = function(url) {
alert("url:"+url);
}
this.loaddata(userid) {
alert("loading data");
}
}
var objMyContent = new myContent();
objMyContent.loadMainLabel("www.google.com");
objMyContent.loaddata("Here I want to access the userID 1234 which I got in the class ");
但是,我不确定如何访问它&我是否以正确的方式前进。任何想法将不胜感激。
答案 0 :(得分:1)
OO类型JS编程的一种更典型的模式是通过函数原型声明类:
function MyClass() {
this.instanceVariable = 10;
this.doSomething();
}
//Extend a "super class"
MyClass.prototype = Object.create(SuperClass.prototype);
MyClass.prototype.doSomething = function() {
...
};
然后,您可以通过new
实例化MyClass:
var myObject = new MyClass();
这里有一个非常好的运行:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
答案 1 :(得分:0)
试试这个:
function myContent() {
this.toUserID = "1234";
this.loadMainLabel = function(url) {
alert("url:"+url);
}
this.loaddata = function(userid) {//here you can get toUserId just by this.toUserId
alert("loading data"+ userid);
}
}
var objMyContent = new myContent();
objMyContent.loadMainLabel("www.google.com");
objMyContent.loaddata(objMyContent.toUserID);
答案 2 :(得分:0)
var MyClass(arg1, arg2) {
var that = {}, privateMember = arg1;
that.constructorArg2 = arg2;
var privateMethod() {
}
that.getPrivateMember() {
return privateMember; // Getters!
}
that.method1(methodArg) {
// do Something
}
that.method2() {
// do something more
privateMethod(); // Calling a private method
}
return that;
}
然后你可以这样做:
var myClass = MyClass(1, 2); // CALL WITHOUT NEW KEYWORD!
myClass.method1();
alert(that.constructorArg2);
alert(that.getPrivateMember());
使用此技术,您可以定义私有方法,私有成员及其getter / setter!
阅读class definitions的这篇文章以及inheritance
的这篇文章