이것을 반환하지 않기 위해 생성자는 어떤 값을 반환 할 수 있습니까?
Javascript의 return 문 this이 new키워드를 사용하여 생성자가 호출 될 때 이외의 값을 반환 할 수있는 정확한 상황은 무엇입니까 ?
예:
function Foo () {
return something;
}
var foo = new Foo ();
내가 착각하지 않으면 something함수가 아닌 프리미티브 인 this경우 반환됩니다. 그렇지 않으면 something반환됩니다. 이 올바른지?
IOW, 어떤 값 something이 필요 (new Foo () instanceof Foo) === false합니까?
정확한 조건은 연산자 [[Construct]]가 사용 하는 내부 속성 에 설명되어 있습니다 new.
ECMA-262 3rd에서. 에디션 사양 :
13.2.2
[[Construct]]개체 의
[[Construct]]속성 이 호출되면 다음 단계가 수행됩니다.FunctionF
- 새 기본 ECMAScript 개체를 만듭니다.
- 의
[[Class]]속성을Result(1)로 설정합니다"Object".- 의 프로토 타입 속성 값을 가져옵니다
F.Result(3)객체 인 경우 의[[Prototype]]속성을Result(1)로 설정합니다Result(3).- 경우
Result(3)객체가 아닌 상기 세트[[Prototype]]의 속성을Result(1)원래로Object에 기재된 프로토 타입 객체 15.2.3.1 .- 인보
[[Call]]의 속성을F제공Result(1)은 ASthis값으로 전달 인수리스트 제공[[Construct]]인수 값으로한다.- 경우
Type(Result(6))입니다Object후 반환Result(6).- 반환
Result(1).
7 단계와 8 단계를 살펴보면 Result(6)( F생성자 함수 에서 반환 된 값) 의 유형이 Object 가 아닌 경우에만 새 객체가 반환됩니다 .
구체적인 예 http://jsbin.com/zivivucahi/1/edit?html,js,console,output
/*
ECMA 262 v 5
http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
"4.3.2
primitive value
member of one of the types Undefined, Null, Boolean, Number, Symbol, or String as defined in clause 6"
*/
var Person = function(x){
return x;
};
console.log(Person.constructor);
console.log(Person.prototype.constructor);
console.log(typeof(Person));
console.log(typeof(Person.prototype));
function log(x){
console.log(x instanceof Person);
console.log(typeof x);
console.log(typeof x.prototype);
}
log(new Person(undefined));
log(new Person(null));
log(new Person(true));
log(new Person(2));
log(new Person(""));
//returns a function not an object
log(new Person(function(){}));
//implementation?
//log(new Person(Symbol('%')));
문제에 대한 문서를 찾을 수 없었지만 귀하가 맞다고 생각합니다. 예를 들어 new Number(5)생성자에서 반환 할 수 있지만 리터럴 5(무시되고 this대신 반환 됨)에서는 반환 할 수 없습니다 .
간단한 단어로 몇 가지 요점을 넣으려고합니다.
자바 스크립트에서 new함수에 키워드 를 사용하면
- 함수는 아무것도 반환하지 않으며 의도 한 객체를 반환합니다.
function User() {
this.name = 'Virat'
}
var user = new User();
console.log(user.name); //=> 'Virat'
- function returns any truthy complex object [object, array, function etc], that complex object takes priority and
uservariable will hold the returned complex object
function User() {
this.name = 'Virat';
return function(){};
}
var user = new User();
console.log(user.name); //=> undefined
console.log(user); //=> function
- function returns any literal, constructor takes priority and it will return an intended object
function User() {
this.name = 'Virat';
return 10;
}
var user = new User();
console.log(user.name); //=> 'Virat'
As a side note, the return value or this is just part of the equation.
For example, consider this:
function Two() { return new Number(2); }
var two = new Two;
two + 2; // 4
two.valueOf = function() { return 3; }
two + 2; // 5
two.valueOf = function() { return '2'; }
two + 2; // '22'
As you can see, .valueOf() is internally used and can be exploited for fun and profit. You can even create side effects, for example:
function AutoIncrementingNumber(start) {
var n = new Number, val = start || 0;
n.valueOf = function() { return val++; };
return n;
}
var auto = new AutoIncrementingNumber(42);
auto + 1; // 43
auto + 1; // 44
auto + 1; // 45
I can imagine this must have some sort of practical application. And it doesn't have to be explicitly a Number either, if you add .valueOf to any object it can behave as a number:
({valueOf: function() { return Math.random(); }}) + 1; // 1.6451723610516638
You can exploit this to make an object that always returns a new GUID, for instance.
When you are using the new keyword, an object is created. Then the function is called to initialise the object.
There is nothing that the function can do to prevent the object being created, as that is done before the function is called.
'programing tip' 카테고리의 다른 글
| Android 지원 디자인 TabLayout : Gravity Center 및 Mode Scrollable (0) | 2020.09.12 |
|---|---|
| 바이너리 데이터를 저장하기위한 VarBinary vs Image SQL Server 데이터 유형? (0) | 2020.09.12 |
| "타사"란 정확히 무엇입니까? (0) | 2020.09.12 |
| git bare 저장소에서 마지막 커밋을 어떻게 해제 할 수 있습니까? (0) | 2020.09.12 |
| memset () 반환 값의 용도는 무엇입니까? (0) | 2020.09.12 |