I'm trying to define a method inside the constructor to modify the 'name' attribute (but it doesn't seem to work).I can't figure out what's wrong with my code(I'm newbie). Thanks in advance.
function Animal(){
this.name=""
this.setName=function(name){
this.name=name
}
}
var myDog=new Animal()
myDog.setName="Max"
console.log(myDog.name)//" "
console.log(myDog.setName)//"Max"
setName
is function so change your code to myDog.setName("Max")
function Animal(){ this.name="" this.setName=function(name){ this.name=name } } var myDog=new Animal() myDog.setName("Max") console.log(myDog.name) //console.log(myDog.setName)//"Max"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.