Javascript 调用对象的方法';s原型
我是JS新手,遇到以下问题: 为什么这不起作用/这段代码在做什么Javascript 调用对象的方法';s原型,javascript,oop,prototype,Javascript,Oop,Prototype,我是JS新手,遇到以下问题: 为什么这不起作用/这段代码在做什么 var Test = {}; Test.prop = "test property"; Test.Class1 = function () { } Test.Class1.prototype = { m1: function() { console.log(this.prop); } } Test.Class1.m1(); 我对本规范的理解如下: 创建名为“测试”的新对象 将属性prop添加
var Test = {};
Test.prop = "test property";
Test.Class1 = function () {
}
Test.Class1.prototype = {
m1: function() {
console.log(this.prop);
}
}
Test.Class1.m1();
我对本规范的理解如下:
prototype
链接仅适用于使用新操作符创建的实例
否则,必须显式调用prototype才能访问该方法
let testClass = new Test.Class1();
testClass.m1();
另外,因为您正在尝试访问prop
属性
Test.Class1.prototype = {
m1: function() {
console.log(this.prop);
}
}
调用站点是
Test.Class1
,prop
应该是Test.Class1
的一部分,而不是在Test
上。我更改了事物的名称,但这应该是有效的
var Person = function(){
this.message = "Hello, world!";
};
Person.prototype = Object.create(Object.prototype);
Person.prototype.constructor = Person;
Person.prototype.greet = function(){
console.log(this.message);
alert(this.message);
};
var tom = new Person();
tom.greet();
您需要先创建原型的实例,然后才能使用其方法:
var instance = new Test.Class1();
console.log(instance.m1());
即使如此,Test.prop也不是实例的一部分,m1将无法访问它
编辑:下面是一个工作示例:
var test = function() {
this.prop = "A property";
}
test.prototype.m1 = function() {
console.log(this.prop);
}
var instance = new test();
console.log(instance.m1());
在JavaScript中,甚至函数的原型属性也是对象。在创建原型为您定义的对象之前,
Test1.Class1.prototype
只是一个常规对象。基本上,其工作方式与以下代码段相同:
var Test1 = { prototype { m1: function() {} } };
// You're trying to call an undefined function!
Test.m1();
// This is fine
Test1.prototype.m1();
另一方面,当您使用new
操作符时,您正在创建一个新对象,其原型是为构造函数设置的原型。魔法就从这里开始:
当您访问一个属性时,JavaScript的运行时会检查对象,以确定是否有一个名为doStuff
的函数,否则它会在对象的原型上查找它,否则它会在原型的原型上查找它,依此类推
实际上,new
操作符是一个。引入了ECMA脚本5,使一切更加清晰:
var Test1 = {
doStuff: function() {
}
};
// The first parameter of Object.create is
// the object that's going to be the prototype of
// Test1 object!
var object1 = Object.create(Test1);
// This works too!
object1.doStuff();
也许你应该检查一下其他问答:不仅仅是。关于
对象。创建:D
var Test1 = {
doStuff: function() {
}
};
// The first parameter of Object.create is
// the object that's going to be the prototype of
// Test1 object!
var object1 = Object.create(Test1);
// This works too!
object1.doStuff();