-
Creating Objectjavascript 2020. 5. 27. 18:29
var Person = function(name,yearOfBirth, job){ this.name = name; this.yearOfBirth = yearOfBirth; this.job = job; } Person.prototype.calculateAge = function(){ console.log(2020 - this.yearOfBirth); } Person.prototype.lastNAme = 'Smith'; var john = new Person('John',1999,'teacher'); //instantiation var mark = new Person('Mark',1979,'retired'); john.calculateAge(); //21 mark.calculateAge(); //41 console.log(john.lastNAme); //'Smith' console.log(mark.lastNAme); //'Smith'
//Object.create var personProto = { calculateAge : function(){ console.log(2020 - this.yearOfBirth); } } //방법1 var john = Object.create(personProto); john.name = 'John'; john.yearOfBirth = 1990; john.job = 'teacher'; //방법2 var mark = Object.create(personProto,{ name: {value : 'Mark'}, yearOfBirth : {value:1980}, job: {value : 'designer'} });
Primitive VS Object
// Primitives vs objects //Primitive var a = 23; var b = a; a = 46; console.log(a); //46 console.log(b); //23 //Object var obj1 = { name : "John", age : 23 } var obj2 = obj1; obj1.age = 30; console.log(obj1.age); //30 console.log(obj2.age); //30 //Functions var age = 27; var obj = { name : 'Jonas', city : 'Lisbon' }; function change(a,b){ a = 30; b.city = 'SanFrancisco' } change(age,obj); console.log(age); //27 console.log(obj.city); //SanFrancisco /*when pass a primitive into the function a simple copy is created. So we can change 'a' as much as we want, it will never affect the variable on the outside because it is a primitive. But when we pass the object, it's not really the object that we pass, but the reference to the object. */
오브젝트를 변수에 담을때 변수에 실제로 들어가는 값은 오브젝트 그 실제 값이 아니라 오브젝트의 레퍼런스가 들어간다.
참조 : Udemy - The Complete JavaScript Course 2020 : Build Real Projects!
https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work 여기서 두번째 답변
How does the "this" keyword work?
I have noticed that there doesn't appear to be a clear explanation of what the this keyword is and how it is correctly (and incorrectly) used in JavaScript on the Stack Overflow site. I have witne...
stackoverflow.com
https://jojoldu.tistory.com/7?category=635878
prototype 이란?
우선 이 포스트는 http://insanehong.kr/post/javascript-prototype/#toc_291 를 읽고 나름 정리와 추가코드를 작성한 것임을 미리 밝히고 시작하겠습니다. 그래서 해당 블로그의 글을 읽고 오시면 더 도움이 되�
jojoldu.tistory.com
'javascript' 카테고리의 다른 글
closure (0) 2020.05.28 function (0) 2020.05.28 자바스크립트 this (0) 2020.05.22 자바스크립트 Object (0) 2020.05.22 자바스크립트 예제 (0) 2020.05.22