//代码清单1
<script type="text/javascript">
var message = "this in window"; //这一句写在函数外面和里面是一样效果
function func() {
if(this == window){
alert("this == window");
alert(message);
this.methodA = function() {
alert("I'm a function");
}
}
}
func(); //如果不调用func方法,则里面定义的属性或方法会取不到
methodA();
</script>
<script type="text/javascript">
function Func() {
if (this == window) {
alert("this == window");
}
else {
alert("this != window");
}
this.fieldA = "I'm a field";
alert(this);
}
var obj = new Func();
alert(obj.fieldA); //this指向的是对象obj
</script>
//代码清单3
<script type="text/javascript">
var obj = {
x: 3,
doit: function(){
if(this == window){
alert("this == window");
}else{
alert("method is called: " + this.x);
}
}
};
obj.doit(); //this指向的是对象obj
</script>
//代码清单4
<script type="text/javascript">
var obj = {
x: 3,
doit: function(){
alert("method is called: " + this.x);
}
};
var obj2 = {x: 4};
obj.doit(); //3,this指向obj
obj.doit.apply(obj2); //4,this指向obj2
obj.doit.call(obj2); //4,this指向obj2
</script>
//代码清单5
<script type="text/javascript">
function Func() {
this.fieldA = "I'm a field";
var privateFieldA = "I'm a var";
}
Func.prototype = {
ExtendMethod: function(str) {
alert(str + " :" + this.fieldA);
alert(privateFieldA); //出错,私有字段无法通过原型链获取。
}
};
var obj = new Func();
obj.ExtendMethod("From prototype"); //此时构造函数及原型链中的this指向对象obj
</script>
//代码清单6
<script type="text/javascript">
var name = "The window";
var obj = {
name: "My Object",
getNameFunc: function(){
return function(){
return this.name;
}
}
};
alert(obj.getNameFunc()()); //The window
</script>
//代码清单7
<script type="text/javascript">
var name = "The window";
var obj = {
name: "My Object",
getNameFunc: function(){
var that = this;
return function(){
return that.name;
}
}
};
alert(obj.getNameFunc()()); //My object
</script>
//代码清单8
<script type="text/javascript">
function a() {
alert(this == window);
var that = this;
var func = function() {
alert(this == window);
alert(that);
};
return func;
}
var b = a();
b(); //true, true, [object Window]
var c = new a();
c(); //false, true, [object object]
</script>
//代码清单9
<script type="text/javascript">
window.color = "red";
var obj = {color: "blue"};
function sayColor(){
alert(this.color);
}
var objSayColor = sayColor.bind(obj);
objSayColor(); //blue
</script>
//代码清单10
<div onclick="test(this)" id="div">Click Me</div>
<script type="text/javascript">
function test(obj) {
alert(obj); //[object HTMLDivElement]
}
</script>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有