如何使用参数调用分配给变量的函数

时间:2018-11-29 13:26:39

标签: javascript angular

我有这样的结构:

//function declaration
someFunc() = {
 // ...
}

//assign function to variable
let f = someFunc();

//call
f();

我想通过变量调用此函数,将参数传递给someFunc(),例如:

f(arg); 

,但是f不是变量。如何通过这种方式处理参数?

编辑: 在上面的问题中,我考虑过通过变量调用函数。像这样:

{{ F }}

并将f分配给返回一些值的函数。

之所以这样做,是因为我需要在ngOnInit生命周期中初始化函数(我的目标是只调用函数一次)。

我的视图和以下ts代码:

TS:

import {Component, OnInit, Input} from '@angular/core';
import {Router} from "@angular/router";
import {PostsService} from "../../services/posts.service";
import {AuthService} from "../../services/auth.service";
import {ConfirmationModalService} from "../../services/confirmation-modal.service";
import {LoaderService} from "../../services/loader.service";
import {ToastService} from "../../services/toast.service";

declare var M: any;

@Component({
    selector: 'app-posts',
    templateUrl: './posts.component.html',
    styleUrls: ['./posts.component.scss']
})
export class PostsComponent implements OnInit {
    avatar: string;
    loggedUser: any;
    modalId: any;
    editModal: any;
    editModalInstance: any;
    content: string;
    contentEdited: string;
    orderSelect: any;
    orderSelectInstance: any;
    showButton: boolean;
    getAvatar: any;

    constructor(private postsService: PostsService, private authService: AuthService,
                private router: Router, private confirmationModalService: ConfirmationModalService,
                private loaderService: LoaderService, private toastService: ToastService) {
    }

    ngOnInit() {

        this.showButton = true;

        this.editModal = document.querySelector('#edit-modal');
        this.editModalInstance = M.Modal.init(this.editModal);

        this.orderSelect = document.querySelectorAll('#post-order-select');
        this.orderSelectInstance = M.FormSelect.init(this.orderSelect);

        this.orderSelect = 'post_date';

        this.loggedUser = localStorage.getItem('user') ?
            JSON.parse(localStorage.getItem('user')).id : '';

        this.loaderService.isLoading = true;

        this.postsService.getPosts().subscribe(response => {
            this.postsService.getPostHandling(response);
            this.loaderService.hideLoader();
        }, err => {
            this.toastService.error(err);
            this.loaderService.hideLoader();
            return false;
        });

        this.getAvatar = this.getCreatorAvatar(123);
    }

    loadMore() {
        this.loaderService.isLoadingSmall = true;
        if (this.orderSelect === 'post_date') {
            this.postsService.getPosts(true).subscribe(response => {
                if (this.postsService.postIndex > response.posts.length) {
                    this.showButton = false;
                }
                this.postsService.getPostHandling(response);
                this.loaderService.hideLoaderSmall();
            }, err => {
                this.toastService.error(err);
                this.loaderService.hideLoaderSmall();
                return false;
            });
        } else if (this.orderSelect === 'rate') {
            this.postsService.getPostsOrdered(true).subscribe(response => {
                if (this.postsService.postIndex > response.posts.length) {
                    this.showButton = false;
                }
                this.postsService.getPostHandling(response);
                this.loaderService.hideLoaderSmall();
            }, err => {
                this.toastService.error(err);
                this.loaderService.hideLoaderSmall();
                return false;
            });
        }
    }

    order(orderSelect) {
        this.loaderService.isLoading = true;
        if (orderSelect === 'post_date') {
            this.postsService.getPosts().subscribe(response => {
                this.postsService.getPostHandling(response);
            }, err => {
                this.toastService.error(err);
                return false;
            });
        } else {
            this.loaderService.isLoading = true;
            this.postsService.getPostsOrdered().subscribe(response => {
                this.postsService.getPostHandling(response);
            }, err => {
                this.toastService.error(err);
                return false;
            });
        }
        this.loaderService.hideLoader();
    }

    onEditModalSubmit() {
        this.editModalInstance.close();
        this.postsService.editPost(this.modalId, this.contentEdited).subscribe(data => {

            if (data.success) {
                this.loaderService.isLoading = true;
                this.postsService.getPosts().subscribe(response => {
                    this.postsService.getPostHandling(response);
                }, err => {
                    this.toastService.error(err);
                    return false;
                });
                this.loaderService.hideLoader();
                this.toastService.success(data.msg);
            } else {
                console.log('some error');
            }
        });
    }

    openEditModal(id, content) {
        this.modalId = id;
        this.editModal.querySelector('#textarea-edit').value = content;
        this.editModalInstance.open();
    }

    deletePost(id) {
        this.confirmationModalService.content = 'Are you sure you want to delete this post?';
        this.confirmationModalService.cta = 'Delete';
        this.confirmationModalService.proceed = () => {
            this.postsService.deletePost(id).subscribe(data => {
                if (data.success) {
                    this.toastService.success(data.msg);
                    this.loaderService.isLoading = true;
                    this.postsService.getPosts().subscribe(response => {
                        this.postsService.getPostHandling(response);
                        this.loaderService.hideLoader();
                    }, err => {
                        this.toastService.error(err);
                        return false;
                    });
                } else {
                    this.toastService.error(data.msg);
                }

            });
            this.authService.decreasePostAmount(JSON.parse(localStorage.getItem('user')).id)
                .subscribe(() => {
                });
            this.confirmationModalService.modalInstance.close();
        };
        this.confirmationModalService.modalInstance.open();
    }

    ratePost(id, creator_id) {
        this.postsService.ratePost(id, creator_id).subscribe(() => {
            if (this.orderSelect === 'post_date') {
                this.postsService.getPosts().subscribe(response => {
                    this.postsService.getPostHandling(response);
                }, err => {
                    this.toastService.error(err);
                    return false;
                });
            } else if (this.orderSelect === 'rate') {
                this.loaderService.isLoading = true;
                this.postsService.getPostsOrdered().subscribe(response => {
                    this.postsService.getPostHandling(response);
                    this.loaderService.hideLoader();
                }, err => {
                    this.toastService.error(err);
                    this.loaderService.hideLoader();
                    return false;
                });
            }
        });
    }

    revertRate(id, loggedUser_id) {
        this.postsService.revertRatePost(id, loggedUser_id).subscribe(() => {
            if (this.orderSelect === 'post_date') {
                this.postsService.getPosts().subscribe(response => {
                    this.postsService.getPostHandling(response);
                }, err => {
                    this.toastService.error(err);
                    return false;
                });
            } else if (this.orderSelect === 'rate') {
                this.loaderService.isLoading = true;
                this.postsService.getPostsOrdered().subscribe(response => {
                    this.postsService.getPostHandling(response);
                    this.loaderService.hideLoader();
                }, err => {
                    this.toastService.error(err);
                    this.loaderService.hideLoader();
                    return false;
                });
            }
        });
    }

    isLiked(users_liked) {
        return users_liked.indexOf(this.loggedUser) > -1;
    }

    getCreatorId(post) {
        return post.creator[0]['id'];
    }

    getCreatorName(post) {
        return post.creator[0]['name'];
    }

    getCreatorAvatar(id) {
        this.authService.getAvatar(id).subscribe(data => {
            this.avatar = data.avatar;
        });
    }
}

HTML:

<div class="row">
    <div class="input-field col s3">
        <select id="post-order-select"
                [(ngModel)]="orderSelect" name="orderSelect" (change)="order(orderSelect)">
            <option value="post_date">Recent posts</option>
            <option value="rate">Most rated</option>
        </select>
        <label>Order by</label>
    </div>
</div>
<div id="post-list" class="post-list">
    <ng-container *ngIf="!loaderService.isLoading">
        <div *ngFor="let post of postsService.posts" class="card-panel first"
             [ngClass]="{'own-post' : authService.loggedIn() && getCreatorId(post) === loggedUser}">
            <div class="post-details">
                <div class="post-header">
                    <div class="author-avatar"
                         [ngStyle]="{ 'background-image' : 'url(' + getAvatar + ')'}">
                    </div>
                    <div class="post-info">
                        <div class="author-fullname grey-text text-darken-3">{{ getCreatorName(post) }}</div>
                        <div class="post-date deep-orange-text">{{ post.post_date | timeago }}</div>
                    </div>
                </div>
                <div class="teaser grey-text text-darken-1" [innerHTML]="post.content"></div>
                <div class="valign-wrapper rate">
                    <ng-container *ngIf="authService.loggedIn() && post.creator.id !== loggedUser">
                        <i *ngIf="!isLiked(post.users_liked)"
                           class="material-icons tiny deep-orange-text text-lighten-4"
                           (click)="ratePost(post._id, loggedUser)">thumb_up</i>
                        <i *ngIf="isLiked(post.users_liked)" class="material-icons tiny deep-orange-text"
                           (click)="revertRate(post._id, loggedUser)">thumb_up</i>
                    </ng-container>
                    <ng-container *ngIf="authService.loggedIn() && post.creator.id === loggedUser">
                        <i class="material-icons tiny deep-orange-text text-lighten-4 own">
                            thumb_up
                        </i>
                    </ng-container>
                    <ng-container *ngIf="!authService.loggedIn()">
                        <i class="material-icons tiny deep-orange-text text-lighten-4 own">
                            thumb_up
                        </i>
                    </ng-container>
                    <span class="grey-text text-darken-3">{{ post.rate }}</span>
                </div>
            </div>
            <ng-container *ngIf="authService.loggedIn() && post.creator.id === loggedUser">
                <a class="btn-floating btn-medium deep-orange darken-3 right"
                   (click)="deletePost(post._id)">
                    <i class="material-icons">delete</i>
                </a>
                <a class="btn-floating btn-medium deep-orange right"
                   (click)="openEditModal(post._id, post.content)">
                    <i class="material-icons">create</i>
                </a>
            </ng-container>
        </div>
        <div *ngIf="loaderService.isLoadingSmall"
             class="row">
            <div class="col s12 center-align">
                <div class="preloader-wrapper small active">
                    <div class="spinner-layer">
                        <div class="circle-clipper left">
                            <div class="circle"></div>
                        </div>
                        <div class="gap-patch">
                            <div class="circle"></div>
                        </div>
                        <div class="circle-clipper right">
                            <div class="circle"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div *ngIf="!loaderService.isLoadingSmall && showButton === true" class="row">
            <div class="col s12 center-align">
                <button (click)="loadMore()" class="btn deep-orange">Load more</button>
            </div>
        </div>
    </ng-container>
</div>

<div *ngIf="loaderService.isLoading" class="row">
    <div class="col s12 center-align">
        <div class="preloader-wrapper big active">
            <div class="spinner-layer">
                <div class="circle-clipper left">
                    <div class="circle"></div>
                </div>
                <div class="gap-patch">
                    <div class="circle"></div>
                </div>
                <div class="circle-clipper right">
                    <div class="circle"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="edit-modal" class="modal">
    <div class="modal-content">
        <form (submit)="onEditModalSubmit()">
            <div class="row">
                <div class="col s12">
                    <div class="input-field deep-orange-text">
                    <textarea id="textarea-edit" [(ngModel)]="contentEdited" name="contentEdited"
                              class="materialize-textarea"></textarea>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col s12">
                    <button type="submit" class="btn grey darken-4 right">Confirm editing</button>
                    <a href="#" (click)="editModalInstance.close()" class="btn grey darken-1 right">Cancel</a>
                </div>
            </div>
        </form>
    </div>
</div>

4 个答案:

答案 0 :(得分:4)

声明

let f = someFunc();

将调用 结果 someFunc()分配给f。如果您希望f是对函数本身的引用,则需要

let f = someFunc;

对函数的引用,后跟()或带括号的参数列表是函数调用。

答案 1 :(得分:1)

您需要分配功能而不调用该功能。

let f = someFunc;

答案 2 :(得分:0)

您需要将不带()的函数分配给如下所示的变量-

const myVar = someFunc;

如果将函数分配给不带括号()的某个变量,它将分配引用。用例中需要的功能。

答案 3 :(得分:0)

添加f作为参考,因此您可以这样做

let f = someFunc

或为其添加功能

let f = someFunc();

或将其用作常量

const f = someFunc(); // f = someFunc