I want to create a class in Java Script. I can use basic functions coupled with prototypes but I want to use Object Literal Notation. Is is possible to create classes using Object Literal Notations?
您不能创建对象的实例(是的,您甚至可以在Javascript中将函数视为对象,但我在谈论的是文字定义的对象),必须使用函数来定义可重用的类。
Cannot be done....well, depends on how you define the params of the requirements. Should be done? Up for debate.
The following is from an idea a coworker of mine had.
http://bit.ly/18xGdKi [JSBin with console example]
if (typeof (makeClass) === "undefined") {
makeClass = function(o) {
var F = function () {};
if (typeof (o) === "object" && o !== null) {
if (typeof (o.constructor) === "function") {
F = o.constructor;
}
F.prototype = o;
}
return F;
};
}
var MyClass = makeClass({
constructor: function (pName) {
var _myPrivateIdaho = 'Idaho ' + pName;
this.name = pName;
var _myPrivateFunc = function() {
console.log('You are in my ' +
_myPrivateIdaho +'.');
};
_myPrivateFunc();
},
getName: function() {
return this.name;
}
});
new MyClass('Bob');
new MyClass('Steve');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.