0

for example

//creating constructor function

function Something(){}

//adding name property to Something prototype


Something.prototype.name='javascript';

is it possible to access name property from its object itself?

//like

Something.name

// but here output will be 'undefined'

// code

function Fan(){}

Fan.prototype.speed='high';

Fan.speed

//output of (Fan.speed) undefined
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56

2 Answers2

1

No, if you set it up as Fan.prototype.speed, then that value is on Fan.prototype.speed and not Fan.speed. When you use Fan as the constructor of an object, that's when the instantiated object is set up with a lookup chain to look up properties that it doesn't have on the constructor's prototype:

const f = new Fan();
console.log(f.speed);  // lookup to Fan.prototype.speed
deceze
  • 510,633
  • 85
  • 743
  • 889
0

You can create an instance of the object and then access it:

function Something() {}
Something.prototype.name = 'javascript';
// create an instance for that
var x = new Something();
console.log(x.name);

//Another set of examples, note the prototype on the objects function has no instance so the getName.protytppe.bucket
const another = {
  secret: "skim",
  name: "cream",
  getName: function() {
    return this.name;
  },
  getSecret: function() {
    return this.secret;
  },
  makeButter: function(n) {
    this.name = n;
    return `We made {this.name} from cream`;
  }
};
another.getName.prototype.bucket = "lot-o-milk"

var n = Object.create(another);
console.log(n.name);
console.log(n.getName());
// make cream into butter
n.name = "butter";
console.log(n.name);
console.log(n.getName());
// turn butter back to cream
delete n.name;
console.log(n.name);
console.log(n.getName());
n.makeButter('yellow');
console.log(n.getName());
console.log(n.getSecret(), n.getName.prototype.bucket);
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100