Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript-尝试从原型中添加原型_Javascript_Html_Oop_Prototype_Subclass - Fatal编程技术网

JavaScript-尝试从原型中添加原型

JavaScript-尝试从原型中添加原型,javascript,html,oop,prototype,subclass,Javascript,Html,Oop,Prototype,Subclass,这听起来比应该的容易,但我在尝试解决这个问题时遇到了问题。我的情况基本上是,我可以创建一个将使用prototype的类(例如:函数exportss(){}) 如果我想添加到类中,我可以使用:exportss.prototype.newMethod()='' 那么,为什么如果我在“newMethod”原型中,我就不能再向“Equirss”添加新原型了。我的意思的一个例子是:this.prototype.test\u var1='-它失败了,正如exportss.test\u var1一样 为什么我

这听起来比应该的容易,但我在尝试解决这个问题时遇到了问题。我的情况基本上是,我可以创建一个将使用prototype的类(例如:
函数exportss(){}

如果我想添加到类中,我可以使用:
exportss.prototype.newMethod()=''

那么,为什么如果我在“newMethod”原型中,我就不能再向“Equirss”添加新原型了。我的意思的一个例子是:
this.prototype.test\u var1='
-它失败了,正如
exportss.test\u var1
一样


为什么我无法从一个子类中向类添加更多内容?

您无法通过
此.prototype获取对象的父原型。您必须使用
this.constructor.prototype
(尽管这会影响该类型的所有对象的行为,在本例中是
exportss
)。此代码段将向“hello world”发出警报

function exClass() {};

exClass.prototype.newMethod = function() {
    this.constructor.prototype.test_var1 = 'hello world';
}

obj = new exClass();
obj.newMethod();
alert(obj.test_var1);

对象的原型不是对象上名为
prototype
的属性。函数上的prototype字段是将成为使用该函数创建的对象的原型的对象。对象可以通过
构造函数
函数访问创建它的函数原型。例如,
this.constructor.prototype.test\u var1=''
在大多数情况下都可以工作

我之所以这么说,是因为很多JavaScript引擎都有一个内置的
\uuuuu proto\uuuuuu
,它是对象的原型,可以动态修改,但这在IE中是不受支持的


在ES5中,可以使用Object.getPrototypeOf()可靠地获取原型。例如,您可以说,
Object.getPrototypeOf(this).test_var1=''
在ES5中,它将在现代浏览器中工作,但不在不支持ES5的浏览器中工作。

构造函数
exportss
prototype
属性与
exportss
的实例的
prototype
属性所指的对象不同,这就是
新方法中引用的内容。证明:

function exClass() {}
exClass.prototype.newMethod = function() {
    console.log(this.prototype === exClass.prototype); // false
    console.log(this.prototype); // undefined
}

var obj = new exClass();
obj.newMethod();
输出:

false
undefined
更一般地说,JavaScript中的每个对象都有一个原型对象。函数的
prototype
属性指定使用该函数创建的对象类的原型对象

没有任何东西可以阻止您从另一个函数中修改函数的
原型

exClass.prototype.newMethod = function() {
    exClass.prototype.anotherMethod = function() {}
}
或者更一般地说:

exClass.prototype.newMethod = function() {
    this.constructor.anotherMethod = function() {}
}
但我不推荐