相关疑难解决方法(0)

__proto__ VS. JavaScript中的原型

该图再次显示每个对象都有一个原型.构造函数Foo也有自己__proto__的Function.prototype,它又通过其__proto__属性再次引用到Object.prototype.因此,重复,Foo.prototype只是Foo的一个显式属性,它指的是b和c对象的原型.

var b = new Foo(20);
var c = new Foo(30);
Run Code Online (Sandbox Code Playgroud)

__proto__prototype属性有什么区别?

在此输入图像描述

这个数字来自这里.

javascript prototype prototypal-inheritance javascript-objects

730
推荐指数
17
解决办法
16万
查看次数

将原型添加到JavaScript Object Literal

STORE = {
   item : function() {
  }
};
STORE.item.prototype.add = function() { alert('test 123'); };
STORE.item.add();
Run Code Online (Sandbox Code Playgroud)

我一直想弄清楚这有什么问题.为什么这不起作用?但是,当我使用以下内容时它可以工作:

STORE.item.prototype.add();
Run Code Online (Sandbox Code Playgroud)

javascript prototype object-literal

55
推荐指数
2
解决办法
3万
查看次数

将原型添加到对象文字中

比方说son,我有一些对象,我想从另一个对象继承father.

当然我可以为父亲创建一个构造函数

Father = function() {
  this.firstProperty = someValue;
  this.secondProperty = someOtherValue;
}
Run Code Online (Sandbox Code Playgroud)

然后使用

var son = new Father();
son.thirdProperty = yetAnotherValue;
Run Code Online (Sandbox Code Playgroud)

但这不是我想要的.由于son将具有许多属性,因此将子声明为对象文字将更具可读性.但后来我不知道如何设置它的原型.

做点什么

var father = {
  firstProperty: someValue;
  secondProperty: someOtherValue;
};
var son = {
  thirdProperty: yetAnotherValue
};
son.constructor.prototype = father;
Run Code Online (Sandbox Code Playgroud)

不会起作用,因为原型链似乎是隐藏的而不关心构造函数.prototype的变化.

我想我可以__proto__在Firefox中使用该属性,比如

var father = {
  firstProperty: someValue;
  secondProperty: someOtherValue;
};
var son = {
  thirdProperty: yetAnotherValue
  __proto__: father
};
son.constructor.prototype = father;
Run Code Online (Sandbox Code Playgroud)

但是,据我所知,这不是该语言的标准功能,最好不要直接使用它.

有没有办法为对象文字指定原型?

javascript oop prototype-programming

7
推荐指数
1
解决办法
4239
查看次数