【问题标题】:read typescript class member inside javascript function在javascript函数中读取typescript类成员
【发布时间】:2018-05-08 12:25:25
【问题描述】:

这是我的代码:

    export class CustomToast implements OnInit {
            toastTypeGroup: string;
            message: string;
            title: string; 
            showDuration= "300";

            constructor(_toastTypeGroup: string, _message:string, _title: string ){
                this.toastTypeGroup = _toastTypeGroup;
                this.message = _message;
                this.title =  _title;
            }

            ngOnInit() {
                **//this is the solution** 
                **var _this = this;**
                console.log(this.showDuration);
                var ToastrDemo = function () {
                    var toastr: any = (<any>window).toastr;
                    var k, m = -1, f = 0;

                    var t = function () {
                        var t, o,
                            //toastTypeGroup
                            e = this.toastTypeGroup,
                            //message
                            n = this.message,
                            //title
                            a = this.title,
                            //showDuration
                            i = this.showDuration,
                    };

                    return { init: function () { t() } }
                }();jQuery(document).ready(function () { ToastrDemo.init() });

            }



        }

我的问题是我想从名为 CustomToast 的类中读取成员值在我的 JavaScript 函数中调用 var t = function () {...}。

我无法获得 typescript 类成员值 inside JavaScript 函数。 例如“toastTypeGroup”成员在我的功能之外无法访问 这是个大问题。

提前致谢。

【问题讨论】:

  • 您可以尝试使用箭头回调:let ToastrDemo = () =&gt; { ... let t = () =&gt; { ... } };return { init: () =&gt; { t() } }jQuery(document).ready(() =&gt; { ToastrDemo.init() });。简而言之,将每次出现的function() 替换为() =&gt;
  • 谢谢大家。我只是在调用 ToastrDemo 函数之前移动了这一行“var _this = this;”。而且我已经将我的帖子更新为正确的行为。

标签: javascript jquery angular typescript oop


【解决方案1】:

移动

var _this = this;

到 ngOnInit 的开头并使用 _this.showDuration 或使用 bind(this)

【讨论】:

  • 谢谢大家。我只是在调用 ToastrDemo 函数之前移动了这一行“var _this = this;”。而且我已经将我的帖子更新为正确的行为。
【解决方案2】:

不确定我是否理解了这个问题,但您不会将.bind(this) 添加到您对t 的定义中吗?

var t = function () {
    var t, o,
        //toastTypeGroup
        e = this.toastTypeGroup,
        //message
        n = this.message,
        //title
        a = this.title,
        //showDuration
        i = this.showDuration,
}.bind(this);

【讨论】:

  • 不工作!可能是因为 T fucntion 它在里面 var ToastrDemo = function () {..} 你觉得呢?
  • 谢谢大家。我只是在调用 ToastrDemo 函数之前移动了这一行“var _this = this;”。而且我已经将我的帖子更新为正确的行为。
【解决方案3】:

【讨论】:

  • 谢谢大家。我只是在调用 ToastrDemo 函数之前移动了这一行“var _this = this;”。而且我已经将我的帖子更新为正确的行为。
猜你喜欢
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 2011-04-06
  • 2013-09-25
相关资源
最近更新 更多