我有一个构造函数,它注册一个事件处理程序:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', function () {
alert(this.data);
});
}
// Mock transport object
var transport = {
on: function(event, callback) {
setTimeout(callback, 1000);
}
};
// called as
var obj = new MyConstructor('foo', transport);Run Code Online (Sandbox Code Playgroud)
但是,我无法data在回调中访问已创建对象的属性.它看起来this并不是指创建的对象,而是指另一个对象.
我还尝试使用对象方法而不是匿名函数:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', this.alert);
}
MyConstructor.prototype.alert = function() {
alert(this.name);
};
Run Code Online (Sandbox Code Playgroud)
但它表现出同样的问题.
如何访问正确的对象?
我正试图在我的Ionic 2应用程序中使用ThreeJS实现一个非常基本的动画.基本上是试图旋转立方体.但是多维数据集不会旋转,因为requestAnimationFrame只在render循环中执行一次.
没有旋转动画.我在下面分享我的代码.
home.html的
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<div #webgloutput></div>
</ion-content>
Run Code Online (Sandbox Code Playgroud)
home.ts
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as THREE from 'three';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
@ViewChild('webgloutput') webgloutput: ElementRef;
private renderer: any;
private scene: any;
private camera: any;
private cube: any;
constructor(public navCtrl: NavController) {
}
ngOnInit() {
this.initThree();
}
initThree() {
this.scene = new THREE.Scene();
this.camera = …Run Code Online (Sandbox Code Playgroud) 不确定我是否完全理解我在这里找到的类似问题的答案,所以要绝对确定:
我想在函数中有一个局部变量,只初始化一次(类似于 C、C++ 等强类型语言中的静态变量)。
当然,我可以全局声明它,但将它放在该函数的范围内似乎更好,因为它不会在其他任何地方使用。
现在,这就是我要做的:
function func(data) {
func.PARAMS = [
{"name": "from", "size": 160, "indexed": true},
{"name": "input", "size": 256, "indexed": false},
{"name": "output", "size": 256, "indexed": false},
];
...
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,func.PARAMS确实只会初始化一次,还是每次调用函数时都会初始化?
根据我找到的一些答案(例如这个答案),我需要在初始化之前使用以下内容:
if (typeof func.PARAMS == 'undefined')
Run Code Online (Sandbox Code Playgroud)
当然,这种“补充”在强类型语言中是无关紧要的,所以我只想确保它是绝对必要的,以确保“静态行为”(即,一次性初始化)。