篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript JS -OOP方式 - SO + DJPW.cz相关的知识,希望对你有一定的参考价值。
// define the objects:
var objLit = {
x: 0,
y: 0,
z: 0,
add: function () {
return this.x + this.y + this.z;
}
};
var ObjCon = function(_x, _y, _z) {
var x = _x; // private
var y = _y; // private
this.z = _z; // public
this.add = function () {
return x + y + this.z; // note x, y doesn't need this.
};
};
// use the objects:
objLit.x = 3;
objLit.y = 2;
objLit.z = 1;
console.log(objLit.add());
var objConIntance = new ObjCon(5,4,3); // instantiate an objCon
console.log(objConIntance.add());
console.log((new ObjCon(7,8,9)).add()); // another instance of objCon
console.log(objConIntance.add()); // same result, not affected by previous line
//fake instance for literal object :)-
var myExplorer = function(settings) {
var o = {
init: function() {
this.somevalue = settings;
},
whatever: function() {
}
};
o.init();
return o;
};
var exp1 = myExplorer('something');
var exp2 = myExplorer('anything');
console.log(exp1.somevalue); //something
console.log(exp2.somevalue); //anything
var myExplorer = function() {
var init = function(settings) {
var config = {
$wrapper : $('#explorerCategories'),
$contentHolder : $j('#categoryContent'),
loadingImg : '<img src="../images/standard/misc/ajax_loader.gif" alt="loading" class="loading" />'
}
// provide for custom configuration via init()
if (settings && typeof(settings) == 'object') {
$.extend(config, settings);
}
// some more code...
},
var createExpanderLink = function() {
// more code
},
var anotherMethod = function() {
// etc
}
// Public API
// return the functions you want to use outside of the current instance
return {
init : init,
createExpanderLink : createExpanderLink,
anotherMethod : anotherMethod
}
}
var firstExplorer = new myExplorer();
var secondExplorer = new myExplorer();
// etc
var Test = (function () {
function _insert() {
console.log(this);
$("#a").html(this.text);
}
function Test() {
this.text = 'Pokusný text';
}
Test.prototype.run = function () {
_insert.call(this);
};
return Test;
})();
$(document).ready(function(){
var x = new Test();
x.run();
});
//@see: https://stackoverflow.com/questions/2709612/using-object-create-instead-of-new
// standard way
var UserA = function(nameParam) {
this.id = MY_GLOBAL.nextId();
this.name = nameParam;
}
UserA.prototype.sayHello = function() {
console.log('Hello '+ this.name);
}
var bob = new UserA('bob');
bob.sayHello();
// with new E5 Object.create()
var userB = {
init: function(nameParam) {
this.id = MY_GLOBAL.nextId();
this.name = nameParam;
},
sayHello: function() {
console.log('Hello '+ this.name);
}
};
var bob = Object.create(userB);
bob.init('Bob');
bob.sayHello();
以上是关于javascript JS -OOP方式 - SO + DJPW.cz的主要内容,如果未能解决你的问题,请参考以下文章