简体   繁体   中英

Need explaination of this Javascript code

<p id="demo"></p>

<script>
function employee(name, jobtitle, born) {
    this.name=name;
    this.jobtitle=jobtitle;
    this.born=born;
}


var fred = new employee("Fred Flintstone", "Caveman", 1970);
document.getElementById("demo").innerHTML = employee.name;
</script>

When I execute this code I get output as : employee But if I execute employee.jobtitle in place of employee.name like:
document.getElementById("demo").innerHTML = employee.jobtitle

I get output as : undefined. Why ?

When you ask for employee.name what you are in fact asking for is the name of the function . Now this appears to be new functionality that has appeared in ES6 , so while this may work in current browsers which have already started implementing the ES6 standards, I'll bet my last fiver that it doesn't work in older browsers like IE8, simply because they don't support ES6.

The reason employee.jobtitle returns undefined is because there is no native property called jobtitle as part of Function.prototype unlike name .

Remember, employee is a constructor, and it's fred that's the object instance in this case. fred.name and fred.jobtitle will give you the property values of that object like you would expect.

employee is a function, it doesn't have a name property.

fred , on the other hand, is an object which was built by that function. It does have a name property.

Try:

document.getElementById("demo").innerHTML = fred.name;

In object-oriented programming, you reference specific instances of a type to interact with them. Not the type itself.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM