这里的this指针为什么是指向上一级调用者 //定义声明这样一个类function User() { this.name = "LiXin"; this.say = function () { alert(this.name); } }然后进行实例化var test=new User().say();实例化的时候,在say函数里面的this为什么不是指向的say,而是指向的User呢?say也是一个function,new的时候为什么是new User,而不是new say? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 在这里say()方法相当于User的一个变量,只是这个变量是方法的形式。为什么是new User,而不是new say?,你见过new变量的吗?,嘿嘿,这是个人理解,希望对你有帮助。 会不会是在new User的时候,this.say就这句已经把say作为User的方法了,所以这个方法里的this也是指的User,不过就是不知道我这样理解是不是对的 实例化后就是一个对象了 this总是指向调用它的对象 当你new一个对象的时候function User() { this.name = "LiXin";//这个this就是那个new 的对象, this.say = function () {//用这个对象调用方法,方法里面的this就是外面调用他的对象 alert(this.name); } }当你不new对象时,直接User()调用的话function User() { this.name = "LiXin";//这个this一般就是window this.say = function () {//用这个对象调用方法,方法里面的this就是外面调用他的对象 alert(this.name); } }因为这个function User() {类,他是定义在window下的,所以可以理解为window.User();这样的调用.并不一定User();调用里面的this就是this,那要看实际的运行环境了。 当一个function被当做一个对象的方法调用的时候, this就指向这个对象。推荐你看 Javascript 语言精粹这本书,很薄的一本。 /*了解了new的基本原理就明白了.*/<script type="text/javascript">// instance --> new 模拟var instance = function(source) { var p = {}; var args = Array.prototype.slice.call(arguments, 1); source.apply(p, args); // 这里p通过apply借用了User的指针 p.__proto__ = source.prototype; return p;}function User() { this.name = "LiXin"; this.say = function() { alert(this.name); }}var test = instance(User).say();</script> instance就是new实现的原理.注释的那句apply知道啥意思.就应该明白了this为啥指向User[source参数就是User] 补充: 以上模拟代码在firefox下运行 我晕. 都写成那样 还看不懂 就补基础吧 apply都不会 那怎么讲? this代表调用当前运行的对象new User().say();new User 代表一个对象. 代表了调用say() 代表了一运行 在new User的时候,this.say就这句表示对say变量的初始化,this当然指的是User啦。 如何快速的获取这个JSon里面的某个具体的值?用each吗? 求个正则谢谢谢谢!!!! js字符串分割求教。 关于网页中的jqgrid表格刷新问题 extjs 怎样判断用户已登录 请教一个弱智的问题? 关于热点链接部分的区域大小的问题javascript 一段很简单的代码: 关于 xmlDom 的,老是出错! 不知道错在哪里? 急的厉害! 一个数组的值,想要在输入框中不断翻滚显示,怎么做? 如何在javascript中实现超级链接?请帮忙!谢谢! 多个文本框联动效果求助 不用提交按钮,文本域内容就能自动提交怎么实现?
为什么是new User,而不是new say?,你见过new变量的吗?,嘿嘿,这是个人理解,希望对你有帮助。
function User() {
this.name = "LiXin";//这个this就是那个new 的对象,
this.say = function () {//用这个对象调用方法,方法里面的this就是外面调用他的对象
alert(this.name);
}
}
当你不new对象时,直接User()调用的话
function User() {
this.name = "LiXin";//这个this一般就是window
this.say = function () {//用这个对象调用方法,方法里面的this就是外面调用他的对象
alert(this.name);
}
}
因为这个function User() {类,他是定义在window下的,所以可以理解为window.User();这样的调用.
并不一定User();调用里面的this就是this,那要看实际的运行环境了。
/*了解了new的基本原理就明白了.*/
<script type="text/javascript">
// instance --> new 模拟
var instance = function(source) {
var p = {};
var args = Array.prototype.slice.call(arguments, 1);
source.apply(p, args); // 这里p通过apply借用了User的指针
p.__proto__ = source.prototype;
return p;
}function User() {
this.name = "LiXin";
this.say = function() {
alert(this.name);
}
}var test = instance(User).say();
</script>
instance就是new实现的原理.注释的那句apply知道啥意思.就应该明白了this为啥指向User[source参数就是User]
补充: 以上模拟代码在firefox下运行
new User().say();
new User 代表一个对象
. 代表了调用
say() 代表了一运行