这是我第一次在 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 ");
但是,我不确定如何访问它以及我是否以正确的方式进行。任何想法将不胜感激。
最佳答案
面向对象类型的 JS 编程更典型的模式是通过函数原型(prototype)声明类:
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
关于javascript - 使用 OOP 访问 Javascript 中定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24256979/