ПРИМЕЧАНИЕ: Я использую ES6 (классы)Что может привести к отказу ключевого слова JavaScript «новое»?
Так что я в настоящее время работает над приложением WinJS Universal (UWP). Я обнаружил, что большую часть времени мой вызов (для определенного класса) работает без каких-либо проблем. Однако, когда я называю это быстро, возвращаемое значение - это сам класс. Я знаю, что ссылка не изменяется, потому что я могу поставить цикл while чуть ниже нее, и она снова начнет работать. Кажется, это какой-то вопрос времени.
Я сломаю на следующий код:
var crop = new $js.Vector2(xCrop, yCrop);
if (!(crop instanceof $js.Vector2)) {
debugger; // This is being hit (not 100% chance, only in rapid use)
}
Однако, если у меня следующее:
var crop = new $js.Vector2(xCrop, yCrop);
while (!(crop instanceof $js.Vector2)) {
crop = new $js.Vector2(xCrop, yCrop);
}
if (!(crop instanceof $js.Vector2)) {
debugger; // This is never hit and the program continues as normal
}
Программа будет продолжать это нормальное выполнение , Также, когда я использую точки останова вокруг этой части кода, чтобы пройти через нее, он работает совершенно нормально; это то, что заставляет меня думать, что это какой-то момент. Я просто пытаюсь выяснить, является ли это ошибкой на стороне Microsoft или на моей стороне.
Вот мой $ js.Vector2 Код:
/**
* A basic 2 dimensional vector
* @class
*/
$js.Vector2 = class {
/**
* @constructor
* @param {number} [x=0] The x dimension of the vector
* @param {number} [y=0] The y dimension of the vector
*/
constructor(x, y) {
/**
* The x dimension of this vector
* @type {number}
*/
this.x = x || 0;
/**
* The y dimension of this vector
* @type {number}
*/
this.y = y || 0;
}
/**
* Copys the x and y dimension of a $js.Vector2 to this one
* @param {number} x
* @param {number} y
*/
set(x, y) {
if (x != null) {
this.x = x;
}
if (y != null) {
this.y = y;
}
}
/**
* Transposes this vector by another vector by shifting (adding)
* @param {$js.Vector2} vector The vector to be added to this vector
*/
move(vector) {
this.x += vector.x;
this.y += vector.y;
}
/**
* Get's the magnitude (pythagorean theorem) of this vector (the length of the hypotenuse of the right triangle produced by this vector)
* @return {number} The length of the hypotenuse
*/
get magnitude() {
return Math.sqrt((this.x * this.x) + (this.y * this.y))
}
/**
* Get's the dot product of this vector and another
* @param {$js.Vector2} vector The vector to be multiplied with this vector
* @return {number} The result of dot product (vector multiplication)
*/
dot(vector) {
return (this.x * vector.x) + (this.y * vector.y);
}
/**
* This will return a new normalized $js.Vector2 of this vector
* @return {$js.Vector2} The normalized $js.Vector2
*/
get normalized() {
var tmp = new $js.Vector2(this.x, this.y);
var mag = this.magnitude;
tmp.x = tmp.x/mag;
tmp.y = tmp.y/mag;
return tmp;
}
/**
* Will get the distance between this vector and another supplied vector
* @param {$js.Vector2} vector
* @return {number} The distance between this $js.Vector2 and the supplied $js.Vector2
*/
distance(vector) {
return Math.sqrt(((vector.x - this.x) * (vector.x - this.x)) + ((this.y - vector.y) * (this.y - vector.y)));
}
/**
* Will subtract this vector from another vector
* @param {$js.Vector2} vector
* @return {$js.Vector2} The result of this vector subtracted by a supplied vector (in that order)
*/
difference(vector) {
return new $js.Vector2((this.x - vector.x), (this.y - vector.y));
}
/**
* Will add this vector from another vector
* @param {$js.Vector2} vector
* @return {$js.Vector2} The result of this vector added by a supplied vector
*/
sum(vector) {
return new $js.Vector2((this.x + vector.x), (this.y + vector.y));
}
/**
* Will check if this vector's components are equal to the supplied vectors
* @param {$js.Vector2} vector The vector to compare against
* @return {boolean} <c>true</c> if the x, y, and z of both vectors are the same value otherwise <c>false</c>
*/
equals(vector) {
if (!(vector instanceof $js.Vector2)) {
return false;
}
return this.x === vector.x && this.y === vector.y;
}
};
Любая помощь будет оценена. Я бы предпочел не использовать некоторые хак-сервисы для решения этой проблемы, если их можно избежать.
Редактировать: Я просто использовал этот точный код на моем Surface Pro 3, и он работал без каких-либо проблем. Кажется, это проблема с моим настольным компьютером (процессор Intel Core i7-6700K). Это увековечивает мое предположение о том, что проблема связана с быстродействием, увидит, есть ли какие-либо обновления/исправления от MS для VS, связанные с этим.
Что такое ожидаемый результат цикла while? – guest271314
@ guest271314 Цель цикла 'while' - подтвердить мою теорию, что нет ничего плохого в вызове' new $ js.Vector2'. Если у меня нет этого вызова, программа сломается (как видно на изображении) на 'debugger'. Однако, когда я добавляю этот вызов, он начинает работать, и я никогда не ударяю строку 'debugger'. Поэтому, просто вызывая конструктор снова и снова, он в конечном итоге будет оценивать объект, а не ссылку на класс/функцию. – baflink
Какова цель вызова 'new $ js.Vector2' в' difference' и 'sum'? – guest271314