可能重复:
How to “properly” create a custom object in JavaScript?
是否可以在Javascript中构建新类型?如果“一切都是对象”,那么对象构造函数是用于构造新类型的吗?如果是这样,这会使对象构造函数也类型化构造函数,对吧?非常感谢帮助,早上好Stack Overflow!
答案 0 :(得分:3)
您可以使用以下代码创建新类,并为其添加方法和属性。
function ClassName() { //Private Properties var var1, var2; //Public Properties this.public_property = "Var1"; //Private Method var method1 = function() { //Code }; //Privileged Method. This can access var1, var2 and also public_property. this.public_method1 = function() { //Code }; } //Public Property using "prototype" ClassName.prototype.public_property2 = "Value 2"; //Public Method using "prototype" //This can access this.public_property and public_property2. //But not var1 and var2. ClassName.prototype.public_method2 = function() { //code here } //Create new Objects var obj1 = new ClassName(); //Access properties obj1.public_property1 = "Value1";
您还可以扩展现有的课程。