Можно ли получить доступ к объекту-прототипу функции с помощью самой функции - PullRequest
0 голосов
/ 09 июля 2020

например

//creating constructor function

function Something(){}

//adding name property to Something prototype


Something.prototype.name='javascript';

можно ли получить доступ к свойству name из самого объекта?

// как

Something.name

// but here output will be 'undefined'

// код

function Fan(){}

Fan.prototype.speed='high';

Fan.speed

//output of (Fan.speed) undefined

Ответы [ 2 ]

1 голос
/ 09 июля 2020

Нет, если вы установите его как Fan.prototype.speed, тогда это значение будет на Fan.prototype.speed, а не Fan.speed. Когда вы используете Fan в качестве конструктора объекта, это когда созданный объект настраивается с цепочкой поиска для поиска свойств, которых у него нет в конструкторе prototype:

const f = new Fan();
console.log(f.speed);  // lookup to Fan.prototype.speed
0 голосов
/ 09 июля 2020

Вы можете создать экземпляр объекта и затем получить к нему доступ:

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);
...