I am trying to get this function to get the correct scope for its "this" operator, but no luck. Inside the AssetName = function(options){ code block, I want the "this" to point to the class AssetName. What is it that I am missing? The scope of this right from the beginning is window.
Assetname: function(options){
var Base = WM.Utility.GenericFilter()
options = options;
if (typeof Object.create !== "function") {
// For older browsers that don't support object.create
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
var AssetName = {};
AssetName = function(options){
return function(){
var self = this;
debugger;
// Call the super constructor.
Base.call(this, options);
this.$mod.on('change', '#asset-name-quick-search', self,
this.search);
this.$mod.on('click', '.close', self, this.remove);
this.initTypeAhead();
this.$selectionList = this.$mod.find("#asset-name-selection-list");
this.assetListItems = [];
return this;
}(options, AssetName);
}
// The AssetName class extends the base GenericFilter class.
AssetName.prototype = Object.create(Base.prototype);
AssetName.prototype.initTypeAhead = function(){
var options = {};
options.source = _.pluck(this.collection, 'asset_name');
options.items = 8;
this.$mod.find('#asset-name-quick-search').typeahead(options);
};
AssetName(options);
return AssetName;
},
AssetName = function(options){
return function(){
var self = this;
debugger;
// Call the super constructor.
Base.call(this, options);
this.$mod.on('change', '#asset-name-quick-search', self, this.search);
this.$mod.on('click', '.close', self, this.remove);
this.initTypeAhead();
this.$selectionList = this.$mod.find("#asset-name-selection-list");
this.assetListItems = [];
return this;
}(options, AssetName);
}
change to
AssetName = function(options){
var aa = function(){
var self = this;
debugger;
// Call the super constructor.
Base.call(this, options);
this.$mod.on('change', '#asset-name-quick-search', self, this.search);
this.$mod.on('click', '.close', self, this.remove);
this.initTypeAhead();
this.$selectionList = this.$mod.find("#asset-name-selection-list");
this.assetListItems = [];
return this;
};
aa.call(AssetName,options);
}
In your code, the function aa is called as aa(options); so this is window.
[update]
I fix the bug with the following code:
AssetName = function (options) {
AssetName = function (options) {
var aa = function () {
alert(this);
return this;
};
aa.call(this, options);
}
AssetName.prototype.initTypeAhead = function () {
alert(1);
}
return new AssetName(options);;
};
var test = AssetName();
test.initTypeAhead();
But I suggest how about writing the code like bellow:
AssetName = function (options) {
AssetName = function (options) {
alert(this);
}
AssetName.prototype.initTypeAhead = function () {
alert(1);
}
return new AssetName();
};
var test = AssetName();
test.initTypeAhead();
You cam just move your var self = this out side of the anonymous returned function. Then you can use just use self.
Related
I'm studying Javascript and learning how to use call. I created this script and I don't know why I can't have access to this variable Time.
var MyObject;
(function(MyObject) {
var Runner = (function() {
function Runner(time) {
this.time = time;
}
var myFunctionArray = [];
Runner.prototype.execute = function() {
myFunctionArray[0]();
}
Runner.prototype.newTest = function(index, execute) {
var test = function() {
return execute.call(this);
}
myFunctionArray.push(test);
}
return Runner;
})();
MyObject.Runner = Runner;
})(MyObject || (MyObject = {});
var myNewObj = new MyObject.Runner(1000); myNewObj.newTest('1', function() {
console.log(this.time) //output: undefined
});
So how can I get time value inside newTest function?
Issue is in newTest function
Runner.prototype.newTest = function(index, execute) {
var test = function() {
return execute.call(this);
}
myFunctionArray.push(test);
}
Here this is pointing to test and not Runner. You will have to save context in a variable and then set it in call.
Runner.prototype.newTest = function(index, execute) {
var self = this;
var test = function() {
return execute.call(self);
}
myFunctionArray.push(test);
}
.call + self
var MyObject;
(function(MyObject) {
var Runner = (function() {
function Runner(time) {
this.time = time;
}
var myFunctionArray = [];
Runner.prototype.execute = function() {
myFunctionArray[0]();
}
Runner.prototype.newTest = function(index, execute) {
var self = this;
var test = function() {
return execute.call(self);
}
myFunctionArray.push(test);
}
return Runner;
})();
MyObject.Runner = Runner;
})(MyObject || (MyObject = {}));
var myNewObj = new MyObject.Runner(1000);
myNewObj.newTest('1', function() {
console.log(this, this.time) //output: undefined
});
myNewObj.execute()
.bind
As commented, you can even use .bind
var MyObject;
(function(MyObject) {
var Runner = (function() {
function Runner(time) {
this.time = time;
}
var myFunctionArray = [];
Runner.prototype.execute = function() {
myFunctionArray[0]();
}
Runner.prototype.newTest = function(index, execute) {
myFunctionArray.push(execute.bind(this));
}
return Runner;
})();
MyObject.Runner = Runner;
})(MyObject || (MyObject = {}));
var myNewObj = new MyObject.Runner(1000);
myNewObj.newTest('1', function() {
console.log(this, this.time) //output: undefined
});
myNewObj.execute()
When you declare your Runner function, you've actually declared a function that takes no arguments that then itself declares a function called Runner that takes one argument.
Actually In this code snippet :
Runner.prototype.newTest = function(index, execute) {
var test = function() {
return execute.call(this);
}
myFunctionArray.push(test);
}
this will reference to test variable (as per constructor invocation pattern)
So, to pass right variable cache the value of this in another variable and then pass that to function.
I'm trying to create a function constructor:
var obj = function() {
this.num = 2;
this.func = function() {
// need to access the **instance** num variable here
};
};
var instance = new obj();
I need to access the instance properties from a propery (which is the function func) of the object. But it doesn't work, since this is always the current function..
Store this in a variable which func can access:
var obj = function() {
var _this = this;
_this.num = 2;
_this.func = function() {
console.log(_this.num);
};
};
Please, use well-known approach, store this into separate field:
var obj = function() {
self = this;
self.num = 2;
self.func = function() {
alert(self.num);
// need to access the **instance** num variable here
};
};
var instance = new obj();
This is the pattern I use for the problem:
var obj = function(){
var self = this;
this.num = 2;
this.func = function() {
console.info(self.num);
};
};
var instance = new obj();
The variable self now can be accessed in all function of obj and is always the obj itself.
This is the same then:
var obj = function(){
var self = this;
self.num = 2;
self.func = function() {
console.info(self.num);
};
};
var instance = new obj();
You can do it using the Custom Constructor Functions, used to create a custom constructor and it's accessed without any problem, try it:
var Obj = function () {
this.num = 2;
this.func = function () {
alert("I have " + this.num);
return "I have " + this.num;
};
};
var instance= new Obj();
instance.func();//will return and show I have 2
How to reuse the same constructor function in multiple objects?
Here creditor_group is constructed in both objects.. How to duplicate the Delegate function!?
http://jsfiddle.net/q2nxuhyc/2/
code
var App = {};
App.module_group = function(main, location, table){
this.init = function(){
console.log('init: '+table+' args: '+main+', '+location);
};
this.test = function(){
console.log('test: '+table);
};
};
function Delegate(main, location){
this.table;
this.module_name;
var module;
this.init = function(){
module = new App[this.module_name](main, location, this.table);
module.init();
return module;
};
this.test = function(){
module.test();
};
}
var module_1 = Delegate;
module_1.prototype.table = 'debtor_group';
module_1.prototype.module_name = 'module_group';
var module_2 = Delegate;
module_2.prototype.table = 'creditor_group';
module_2.prototype.module_name = 'module_group';
// This part where the objects are constructed is done in another scope
var m_1 = new module_1('main', 'location');
m_1.init();
m_1.test();
var m_2 = new module_2('main', 'location');
m_2.init();
m_2.test();
console
init: creditor_group args: main, location
test: creditor_group
init: creditor_group args: main, location
test: creditor_group
Sounds like you want to use inheritance with two extra constructors module_1 and module_2 that both call the Delegate:
function Delegate(main, location) {
this.module = null;
this.init = function() { // you should do initialisation stuff directly in the
// constructor, not an `init` method
this.module = new App[this.module_name](main, location, this.table);
this.module.init();
};
}
Delegate.prototype.test = function(){
this.module.test();
};
function Module_1(main, location) {
Delegate.call(this, main, location);
}
Module_1.prototype = Object.create(Delegate.prototype);
Module_1.prototype.table = 'debtor_group';
Module_1.prototype.module_name = 'module_group';
function Module_2(main, location) {
Delegate.call(this, main, location);
}
Module_2.prototype = Object.create(Delegate.prototype);
Module_2.prototype.table = 'creditor_group';
Module_2.prototype.module_name = 'module_group';
I write a extend method to achieve inheritance in javascript:
function Class() {}
Class.prototype.create = function () {
var instance = new this();
instance.init();
return instance;
}
// extend method
Class.extend = Class.prototype.extend = function (props) {
var SubClass = function () {};
SubClass.prototype = Object.create(this.prototype);
for (var name in props) {
SubClass.prototype[name] = props[name];
}
SubClass.prototype.constructor = SubClass;
if (this.prototype.init) {
SubClass.prototype.callSuper = this.prototype.init;
}
SubClass.extend = SubClass.prototype.extend;
SubClass.create = SubClass.prototype.create;
return SubClass;
}
// level 1 inheritance
var Human = Class.extend({
init: function () {
}
});
// level 2 inheritance
var Man = Human.extend({
init: function () {
this.callSuper();
}
})
// level 3 inheritance
var American = Man.extend({
init: function () {
this.callSuper();
}
})
// initilization
American.create();
Then the develop tool report Maximum call stack size exceeded
I think the callSuper method cause the problem, callSuper call init, and init call callSuper, both with the same context.
But I don't know how to fixed it!
Can anyone could help me? How to set the correct context?
You have a scope problem. Here is the solution:
function Class() {}
Class.prototype.create = function () {
var instance = new this();
instance.init();
return instance;
}
// extend method
Class.extend = Class.prototype.extend = function (props) {
var SubClass = function () {},
self = this;
SubClass.prototype = Object.create(this.prototype);
for (var name in props) {
SubClass.prototype[name] = props[name];
}
SubClass.prototype.constructor = SubClass;
if (this.prototype.init) {
SubClass.prototype.callSuper = function() {
self.prototype.init();
}
}
SubClass.extend = SubClass.prototype.extend;
SubClass.create = SubClass.prototype.create;
return SubClass;
}
// level 1 inheritance
var Human = Class.extend({
init: function () {
console.log("Human");
}
});
// level 2 inheritance
var Man = Human.extend({
init: function () {
console.log("Man");
this.callSuper();
}
})
// level 3 inheritance
var American = Man.extend({
init: function () {
console.log("American");
this.callSuper();
}
})
// initilization
American.create();
The key moment is to wrap init method in a closure:
SubClass.prototype.callSuper = function() {
self.prototype.init();
}
Here is a jsfiddle containing the solution http://jsfiddle.net/krasimir/vGHUg/6/
I'm writing my own JavaScript library. How can I do for extend my object in this way?
_.mymethod();
Here's my code:
(function (window, undefined) {
"use strict";
var emptyArray = [];
function _(id) {
return new _.fd.init(id);
}
_.fd = _.prototype = {
init: function (selector) {
this.el = document.getElementById(sel);
return this;
},
replaceText: function (text) {
this.el.innerHTML = text;
return this;
},
changeTextColor: function (color) {
this.el.style.color = color;
return this;
}
};
_.fd.init.prototype = _.fd;
_.extend = function (target) {};
_.extend({});
window._ = _;
}(window));
The point is, how to extend for using method like
_.method();