Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.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_Prototype - Fatal编程技术网

Javascript 如何设置';这';指向属性上方法的对象?

Javascript 如何设置';这';指向属性上方法的对象?,javascript,prototype,Javascript,Prototype,我正在为一个对象创建一个相当大的原型,并尝试将函数收集到属性中,以便根据它们的功能来组织它们。这给了我如下代码: function MyConstructor(name){ this.name = name || 'billy!'; } MyConstructor.prototype.stringFns = {}; MyConstructor.prototype.stringFns.helloWorld = function(){ alert('hello world!'

我正在为一个对象创建一个相当大的原型,并尝试将函数收集到属性中,以便根据它们的功能来组织它们。这给了我如下代码:

function MyConstructor(name){

    this.name = name || 'billy!';

}

MyConstructor.prototype.stringFns = {};

MyConstructor.prototype.stringFns.helloWorld = function(){
    alert('hello world!');
}

MyConstructor.prototype.stringFns.helloMe = function(){
    alert('hello ' + this.name); // <- THIS DOESN'T WORK
}
函数MyConstructor(名称){
this.name=name | |比利;
}
MyConstructor.prototype.stringFns={};
MyConstructor.prototype.stringFns.helloWorld=函数(){
警惕(“你好,世界!”);
}
MyConstructor.prototype.stringFns.helloMe=函数(){
警报('hello'+this.name);//您可以使用
call()
bind()
apply()
来设置
this
的值

var test = new MyConstructor('Dave');

test.stringFns.helloMe.call(test);

“我正在为一个对象创建一个相当大的原型”.建议:不要。我想在创建方法的地方定义它,而不是在调用它们的地方。这可能吗?@ckersch-nope,不是这样,你刚刚在stringFns中创建了一个新的空对象,然后你向该对象添加属性,而构造函数的作用域在这些属性中丢失。