Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Выяснить, что функция вызвана в режиме конструктора (https://javascript.ru/forum/misc/21065-vyyasnit-chto-funkciya-vyzvana-v-rezhime-konstruktora.html)

Octane 27.08.2011 21:59

В третьем сообщении я привел такой же пример решения с помощью дополнительного свойства.

float 27.08.2011 23:18

Цитата:

Не очень хочется иметь ненужное enumerable-свойство в каждом объекте.
Вроде можно и не иметь:
function F(x) {
		if (this.constructor == F && !F.i) {
			F.i = 1;
			this.x = x;
		}
		return this.x;
	}
	
	var f = new F(3), obj = {x: 5};
	
	alert(f.x); //3
	
	alert(F.call(obj)); //5
	alert(F.call(f)); //3

Octane 27.08.2011 23:30

Так конструктор будет одноразовый

float 27.08.2011 23:35

тфу, чуть не так хотел.
function F(x) {
		if (this.constructor == F && !this.constructor.i) {
			this.constructor.i = 1;
			this.x = x;
		}
		return this.x;
	}
	
	var f = new F(3), obj = {x: 5};
	
	alert(f.x); //3
	
	alert(F.call(obj)); //5
	alert(F.call(f)); //3

B@rmaley.e><e 28.08.2011 08:42

Так в этом случае
Цитата:

Сообщение от float
this.constructor == F

же.

float 28.08.2011 11:57

точно. забыл что конструктор это ссылка.

float 28.08.2011 12:50

ну, пожалуй, последний мой вариант:):
function isEmptyObj(obj) {
		var a; for(a in obj) {return false;}
		return true;
	}

	function F(x) {
		if (this.constructor == F && isEmptyObj(this)) {
			this.x = x;
		}
		return this.x;
	}
	
	var f = new F(3), obj = {x: 5};
	
	alert(f.x); // 3
	alert(F.call(obj)); // 5
	alert(F.call(f)); // 3

Octane 28.08.2011 13:58

Только hasOwnProperty надо добавить.


Часовой пояс GMT +3, время: 21:54.