Javascript로 객체를 생성하는 함수를 어떻게 사용합니까?
나는 자바 스크립트로 강의를하고있다. Im "Objects and classes"장에 있고, 숙제에서 과제를 해결하는 방법을 모릅니다. 첫 번째 운동은 이렇게
function createCat(name,age){
//Create a new object with the property "name" and the value defined by the argument "name".
//Add a new property to the object with the name "age" and use the value defined by the argument"age"
//Add a methos (function) called meow that returns the string "Meow"!
}
그리고 이것이 내가 노력하는 것입니다.
function createCat(name,age){
var Cat={};
Cat.Name=name;
Cat.Age=age;
Cat.meow=function(){return "Meow!"};
return Cat;
}
index.html 파일에서 스크립트를로드하고 브라우저에서 해당 파일을 연 다음 웹 콘솔에서 기능을 테스트하는 기능을 테스트합니다. 기능을 실행했는데 문제가 없습니다. 그런 다음 콘솔에 Cat.Name을 작성하여 Cat 개체가 반환되었는지 테스트하여 오류가 발생합니다. 아래 코드 줄에서 함수를 호출 한 다음 Object의 속성에 액세스하려고 할 때도 똑같은 일이 발생합니다. 오류는 "ReferenceError : Cat is not defined"입니다. 내가 도대체 뭘 잘못하고있는 겁니까? 감사!
답변
이를 수행하는 더 깨끗한 방법은 let Cat = {}부품을 완전히 생략하는 것입니다. 함수 자체를 사용하여 Cat개체 를 만들 수 있습니다 .
function Cat(name, age) {
this.name = name;
this.age = age;
this.meow = () => console.log("Meow!");
}
let myCat = new Cat("Waldorf", 16)
let anotherCat = new Cat("Statler", 12)
myCat.meow()
console.log(anotherCat.name)
함수는 Cat을 반환하지만 이것은 함수 범위의 이름 일뿐입니다. 함수에서 해당 이름을 사용하려면 다음을 수행해야합니다.
function createCat(name, age) {
var cat = {};
cat.Name = name;
cat.Age = age;
cat.meow = () => "Meow!";
return cat;
}
let Cat = createCat("mist", 16);
console.log(Cat)
이 오류 Cat는 함수 범위 내에서만 정의 되기 때문에 발생 합니다. Cat전역 적으로 정의하려면 window.Cat대신 사용하십시오 var Cat.
function createCat(name, age) {
window.Cat = {};
Cat.Name = name;
Cat.Age = age;
Cat.meow = function() {
return "Meow!"
};
return Cat;
}
console.log(Cat.Name);
콘솔에 입력 할 때 Cat을 얻으려면 다음 Cat.name과 같이 전역 적으로 선언해야합니다.
function createCat(name, age) {
return {
name: name,
age: age,
meow: function() {
return "Meow!"
},
};
}
window.Cat = createCat('name', 2);
그러면 전 세계적으로 Cat에 액세스 할 수 있습니다.
브라우저 콘솔의 변수에 Cat을 할당하고 Cat.name다음과 같이 액세스 할 수도 있습니다 .
const Cat = createCat('name', 2);