JavaScript/JS 초급&개념
[JS] 6장-2. 함수 호출
개발자엄지희
2023. 6. 13. 21:46
반응형
2-5) 함수 호출
function func(arg1, arg2) {
// debugger // 넣으면 중단점
console.log(arg1, arg2);
}
func(); //undefined undefined
func(1); //1 undefined
func(1, 2); //1 2
func(1, 2, 3); //1 2
매개변수 개수가 맞지 않아도 오류가 나지 않음
함수 호출이 자유로움(오버로딩이 필요 없음)
매개변수는 유사배열이라 push 등 배열 메소드는 없지만 배열처럼 작업하고 싶은 경우
Array.prototype.slice.apply(arguments).push // 이렇게 작업 가능하다
(1) this 바인딩
var obj = {
name: 'max', // 객체 obj에 속함
say: function () {
console.log(this.name);
}
}
obj.say(); //max
this는 프로퍼티를 들고 있음
(2) window는 전역객체
var test = 'test'; // window에 속함
console.log(test) //test
console.log(window.test) //test
var say = function () { // window에 속함
console.log(this.test);
}
say(); //test
var value = 100;
var myObject = {
value: 1,
func1: function () {
this.value += 1; // 2
console.log('func1 is ' + this.value);
func2 = function () { // var를 선언하지 않으면 전역으로 선언됨(window)
this.value += 1; // window.value += 1
console.log('func2 is ' + this.value); // 102
func3 = function () { // 마찬가지로 window에 바인딩됨
this.value += 1; // window.value += 1
console.log('func3 is ' + this.value); // 101
}
func3();
}
func2();
}
}
myObject.func1();
(3) 외부 환경을 뒤지는 클로저, that
var value = 100;
var myObject = {
value: 1,
func1: function () {
var that = this;
this.value += 1;
console.log('func1 is ' + this.value);
func2 = function () {
that.value += 1;
console.log('func2 is ' + that.value);
func3 = function () {
that.value += 1;
console.log('func3 is ' + that.value);
}
func3();
}
func2();
}
}
myObject.func1();
(4) 생성자 함수를 호출하는 this 바인딩
var Person = function (name) {
//1. 빈객체 생성 및 this 바인딩 - 내부적으로는 var this = {}; 이런 느낌
// 부모 객체의 프로토타입 연결this.[[Prototype]] = Person.prototype; 이런 느낌
this.name = name; //2.프로퍼티 생성
//3. 생성된 객체 리턴 - 내부적으로는 return this; 이런 느낌
}
var test = new Person('max');
console.log(test.name); //max
console.dir(Person);
// prototype - constructor를 만들어줌, 이때 constructor는 나 자신을 부름
// [[Prototype]] - 부모 객체와 연결된 프로토타입
console.dir(test);
// prototype
// [[Prototype]] - 부모 객체와 연결된 프로토타입, 즉 Person.prototype
//부모 객체 선언
function Parent (name) { this.name = name }
Parent.prototype.say = function () {return this.name};
//자식 객체 선언
function Child() {Parent.apply(this, arguments)}
//부모 상속
Child.prototype = new Parent();
//인스턴스 생성
var kid = new Child("abc");
console.dir(kid);
// Child
// [[Prototype]]: Parent
// [[Prototype]]: Object
// [[Prototype]]: Object
function Person(name, age) {
this.name = name;
this.age = age;
}
var obj4 = Person('max', 4);
obj4; // undefined - return을 안했으니까, 함수 호출만 한 것
window.name // 'max'
window.age // 4
(5) call과 apply 메소드를 이용한 this 바인딩 - 호출할 때 this 지정함
var obj = {};
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.apply(obj, ['max', 1]); // Person.call(obj, 'max', 1); 과 같다.
obj // age: 1, name: 'max'
window.name // undefined
window.age // undefined
(6) function() {}.bind(this) - 정의할 때 this 지정함
func('key');
function func(one, two, key) {
// key: 'key'
// one: 1
// two: 2
// this: this
}.bind(this, 1, 2);
(7) apply로 유사 배열 배열처럼 사용하기
arr.prototype.slice.apply(arguments)
아규먼츠를 슬라이스 태워서 그걸 리턴 하는 데 apply가 이걸 태워 줌
2-6) 힘수 return이 없으면 생성된 객체가 리턴됨
functinon Person (name, age) {
this.name = name;
this.age = age;
// return {name: 'no name', 20);
}
var test = Person;
test // age: 20, 이름 'no name'
var test = new Person('Jake', 19);
test // age: 19, 이름 'Jake'
2-7) 객체의 프로토타입 체이닝
var myObject = {
name: 'max',
sayName: function () {
console.log(this.name);
}
}
myObject.sayName(); //'max'
console.log(myObject.hasOwnProperty('name'); // true
console.log(myObject.hasOwnProperty('nickName'); // false
myObject.toString(); // 오류 안남 - Object에 있기 때문
console.log(myObject.hasOwnProperty('toString')); // false - myObject가 직접 정의한 건 아니기 때문
2-8) 프로토타입에 값 할당
function Person(name) {
this.name = name;
}
Person.prototype.country = 'korea';
var test1 = new Person("aa");
var test2 = new Person("bb");
console.log(test1.country);//korea
console.log(test2.country);//korea
test1.country = 'USA';
console.log(test1.country);//USA
console.log(test2.country);//korea
JS ES5 클래스에 의한 인스턴스 생성
Javascript ES5 클래스에 의한 인스턴스 생성
해당 포스팅은 자바스크립트에서 객체를 생성하는 방법 중 하나인 "생성자 함수"에 대해 서술한다.
velog.io
반응형