is there a way to repeat the methods in VueJS instance I seemed to try every syntax possible like injecting traditional for-loop and it didn't work. I have no clue and ended up writing the methods myself.
The methods property contains... methods!
You can do whatever you want inside its definition, not outside of it...
methods: {
methodname: function() {
var x = 0;
for(i=0; i<4; i++) {
i += 4;
}
}
}
Hope that helps
Related
Sorry, if it is duplicate, but I didn't find explanation.
How can I create field in js class? to define in the future...
class Polygon {
//var whyNot; This makes false
constructor(height, width) {
this.height = height;
this.width = width;
}
calcArea() {
return this.height * this.width;
}
}
Your understanding of JS objects is a little off... you create a variable that calls the function which is its own constructor. Then you modify the object to contain functions you wish to invoke later. like this https://jsfiddle.net/programndial/vonc5af5/
<input type="button" id="testButton" value="Test" />
function Polygon(height, width) {
this.height = height;
this.width = width;
Polygon.prototype.calcArea = function(string) {
return this.height * this.width;
}
}
testButton.onclick = function() {
var newPoly = new Polygon(10, 25);
alert(newPoly.calcArea());
}
The answer is (partially) in your question.
We will assume from the code and the link in your comment that you use a recent version of Javascript : ES6 or ES2015.
You can create them in the constructor method as in the code you provided.
class Polygon {
constructor(height, width) {
//height and width will be fields of Polygon
this.height = height;
this.width = width;
//...and whyNot too!
this.whyNot = 42;
}
...
Of course, since ES6 is compatible the previous versions of Javascript you still can use constructor methods, object literals...
Check this answer.
Constructors in JavaScript objects
You don't have a 'class' in javascript, you define the object as a function. you define inheritable functions as prototypes. pretty much you would use 'prototype' keyword for oop behavior.
Is there a way to define a property in a TypeScript module?
None of these compile:
module My {
// doesnt work
get Value(): number { return 42; }
// doesn't work either
get function Value(): number { return 42; }
// nope
function get Value(): number { return 42; }
}
Right now I'm forced to use this:
module My {
declare var Value: number;
Object.defineProperty(My, "Value", {
get: () => 42
});
}
The second form seems messy to me and the code hinting doesn't really treat it as a read-only property but as a plain variable.
Is there any standard way of defining properties directly inside modules?
No, there's not a way to declare a property on a module in TypeScript using any documented language features.
You can do it in several slightly round-about techniques.
A module can extend an existing class or function. So, I've created a class with a static property, and then later created a module that uses the same name as the class.
class My
{
static get Value():Number {
return 42;
}
}
module My {
var works: boolean = true;
}
alert(My.Value);
It does generate one oddity in the JavaScript generated code that you wouldn't do manually (and should be removed by most optimizers anyway) ... it will redeclare the variable My when the module is created. This does not cause a run-time issue as the variable was already lifted in JavaScript and will not conflict with the first usage.
Here's another option:
module Global {
class Inner {
get Value():Number {
return 42;
}
}
export var My;
My = new Inner();
}
var My = Global.My;
alert(My.Value);
While it presents an extra namespace, you can manipulate it however you'd like and use the inner class or change it as needed. This way, the My variable is global, just like it would be as a module.
Instead of using the module keyword, consider instead using export, which will allow you to do what you want to do, treating the file itself as a module (which is how CommonJS and AMD both work).
// in My.ts
var My = {
get value() {
return 42;
}
};
export = My;
// in foo.ts
import My = require('My');
console.log(My.value);
I describe this in greater detail in a blog post, The Definitive Guide to TypeScript.
I tried the singleton
let My = {
get value() {
return 42;
}
}
export My
but ran into an issue where the emitted JS still said get value() and didn't work on older versions of Node. I tried Object.defineProperty but then lost TypeScript compatibility. Here's my bridge that fixes both cases:
interface My {
value: number
}
// type assertion fixes TypeScript usage
let my = <My>{}
// defineProperty fixes JS usage
Object.defineProperty(my, 'value', {
get: () => 42
});
export = my;
It's used like a module in typescript
import * as my from './my'
my.property // returns 42
// my.property = doesn't work
I know it's a "little" late for this but using typescript 4.8 you can do this:
export module MyModule {
export var myVariable: string = "test";
}
then use it like:
MyModule.myVariable = "something else";
Say I have a slightly complicated for loop, being used in different situations. Is there a way to extract that forloop and still keep the code readable?
For example:
private function bar(){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
doSomethingA();
}
}
}
private function foo(){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
doSomethingB();
}
}
}
The way I would do this/answer the question is to write something like this:
private function loopFunction(callback:Function){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
callback();
}
}
}
private function bar(){
loopFunction(doSomethingA);
}
private function foo(){
loopFunction(doSomethingB);
}
However I find this approach makes the code rather unreadable at times, as you aren't quite sure who is doing what when. Especially if the function passed in comes from another class. Is there a better way to do this?
Another reason why this sollution may not work is if you need to pass in different parameters to the callback function. For example.
private function bar(){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
doSomethingA(arrayA);
}
}
}
private function foo(){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
doSomethingB(i);
}
}
}
As others have pointed out, higher-order functions such as map, fold, and filter provide this kind of functionality. Of course, the precise implementation will vary by language.
Here's a sample in C#:
var foobarList = arrayA.Where(x => x.someVar == foobar).ToList();
foobarList.ForEach(x => doSomethingA());
foobarList.ForEach(x => doSomethingB());
And VB.NET:
Dim foobarList = arrayA.Where(Function(x) x.someVar = foobar).ToList()
foobarList.ForEach(Function(x) doSomethingA())
foobarList.ForEach(Function(x) doSomethingB())
And Javascript:
var foobarList = arrayA.filter(function(x) { return x.someVar == foobar });
foobarList.forEach(function(x) { doSomethingA(); });
foobarList.forEach(function(x) { doSomethingB(); });
You should stop abstracting when it is making your code worse :)
Many languages have higher level constructs built in to deal with common iteration patterns. C++11 has range-based for loops to make iterating over data structures less tedious. Functional languages often have map, fold and filter.
I'm trying to violate the laws of objective C a little by having static (class level) variables that have setters and getters:
+(CGRect*)defaultOpFr:(CGRect*)set{
static CGRect * defaultOpFr = nil;
if (set) {
if (!defaultOpFr) {
defaultOpFr = malloc(sizeof(defaultOpFr));
}
defaultOpFr->size.width = set->size.width;
defaultOpFr->size.height = set->size.height;
defaultOpFr->origin.x = set->origin.x;
defaultOpFr->origin.y = set->origin.y;
}
return defaultOpFr;
}
It seems to work, but I'm wondering if there's a better way. The idea is to call it with nil to retrieve the value, call it with a CGRect to set a new value.
Yup; that'll work, but be completely against any kind of common pattern.
Why don't you simply have a standard setter/getter pair? Even at the class level, that is fine:
static CGRect barf;
+ (CGRect) barf { return barf; }
+ (void) setBarf:(CGRect)aRect { barf = aRect; }
Done.
Is there a way to run a piece of JavaScript code only ONCE, without using boolean flag variables to remember whether it has already been ran or not?
Specifically not something like:
var alreadyRan = false;
function runOnce() {
if (alreadyRan) {
return;
}
alreadyRan = true;
/* do stuff here */
}
I'm going to have a lot of these types of functions and keeping all booleans would be messy...
An alternative way that overwrites a function when executed so it will be executed only once.
function useThisFunctionOnce(){
// overwrite this function, so it will be executed only once
useThisFunctionOnce = Function("");
// real code below
alert("Hi!");
}
// displays "Hi!"
useThisFunctionOnce();
// does nothing
useThisFunctionOnce();
'Useful' example:
var preferences = {};
function read_preferences(){
// read preferences once
read_preferences = Function("");
// load preferences from storage and save it in 'preferences'
}
function readPreference(pref_name){
read_prefences();
return preferences.hasOwnProperty(pref_name) ? preferences[pref_name] : '';
}
if(readPreference('like_javascript') != 'yes'){
alert("What's wrong wth you?!");
}
alert(readPreference('is_stupid') ? "Stupid!" : ":)");
Edit: as CMS pointed out, just overwriting the old function with function(){} will create a closure in which old variables still exist. To work around that problem, function(){} is replaced by Function(""). This will create an empty function in the global scope, avoiding a closure.
I like Lekensteyn's implementation, but you could also just have one variable to store what functions have run. The code below should run "runOnce", and "runAgain" both one time. It's still booleans, but it sounds like you just don't want lots of variables.
var runFunctions = {};
function runOnce() {
if(!hasRun(arguments.callee)) {
/* do stuff here */
console.log("once");
}
}
function runAgain() {
if(!hasRun(arguments.callee)) {
/* do stuff here */
console.log("again");
}
}
function hasRun(functionName) {
functionName = functionName.toString();
functionName = functionName.substr('function '.length);
functionName = functionName.substr(0, functionName.indexOf('('));
if(runFunctions[functionName]) {
return true;
} else {
runFunctions[functionName] = true;
return false;
}
}
runOnce();
runAgain();
runAgain();
A problem with quite a few of these approaches is that they depend on function names to work: Mike's approach will fail if you create a function with "x = function() ..." and Lekensteyn's approach will fail if you set x = useThisFunctionOnce before useThisFunctionOnce is called.
I would recommend using Russ's closure approach if you want it run right away or the approach taken by Underscore.js if you want to delay execution:
function once(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
return memo = func.apply(this, arguments);
};
}
var myFunction = once(function() {
return new Date().toString();
});
setInterval(function() {console.log(myFunction());}, 1000);
On the first execution, the inner function is executed and the results are returned. On subsequent runs, the original result object is returned.
What about an immediately invoked anonymous function?
(function () {
// code in here to run once
})();
the code will execute immediately and leave no trace in the global namespace.
If this code is going to need to be called from elsewhere, then a closure can be used to ensure that the contents of a function are run only once. Personally, I prefer this to a function that rewrites itself as I feel doing so can cause confusion, but to each their own :) This particular implementation takes advantage of the fact that 0 is a falsy value.
var once = (function() {
var hasRun = 0;
return function () {
if (!hasRun) {
hasRun++;
// body to run only once
// log to the console for a test
console.log("only ran once");
}
}
})();
// test that the body of the function executes only once
for (var i = 0; i < 5; i++)
once();
Elegant solution from Douglas Crockford, spent some time to understand how it works and stumbled upon this thread.
So the wrapper once return function which is just invokes parameter's function you passed. And taking advantage of closures this construction replaced passed function to empty function, or null in original source, after the first call, so all the next calls will be useless.
This is something very close to all other answers, but it is kinda self containing code and you could use it independently, which is good. I am still trying to grasp all the entire mechanism of replacement, but practically it just works perfectly.
function once (func) {
return function () {
var f = func;
func = null;
return f.apply(this, arguments);
};
}
function hi(name) {
console.log("Hi %s", name);
}
sayonce = once(hi);
sayonce("Vasya");
sayonce("Petya");
for those who are curious here is jsbin transformations
(function (){
var run = (function (){
var func, blank = function () {};
func = function () {
func = blank;
// following code executes only once
console.log('run once !');
};
return function(){
func.call();
};
})();
run();
run();
run();
run();
})();
I just ran into this problem, and ended up doing something like the following:
function runOnce () {
if (!this.alreadyRan) {
// put all your functionality here
console.log('running my function!');
// set a property on the function itself to prevent it being run again
this.alreadyRan = true;
}
}
This takes advantage of the fact that Javascript properties are undefined by default.
In addition, the nature of what happens in the "/* do stuff here */" may leave something around that, when present, must mean that the function has run e.g.
var counter = null;
function initCounter() {
if (counter === null) {
counter = 0;
}
}
If not bound to an event, code is usually ran once