this作用域、javascript面向…

来源:互联网 发布:淘宝流程 编辑:程序博客网 时间:2024/05/16 07:57
原文地址:this作用域、javascript面向对象作者:loveflying
此过程模拟了javascript操作符new对象的过程。
var name = "zjx";

var say = function (){
 alert(this.name);
 this.eat = function(){
   alert("eat");
 }
}
this.say();
this.eat();

alert("====================");

var user1 = {
  name : "zff",
  say: this.say
}
user1.say();
user1.eat();

alert("====================");

var user2 = {
 name : "cm",
 say :this.say
}
user2.say();
user2.eat();

alert("====================");

alert(user1.say == user2.say);
alert(user1.eat == user2.eat);

输出:
zjx
eat
====================
zff
eat
====================
cm
eat
====================
True
False

上面代码还夹杂了this的作用域问题,只针对new过程的代码如下:
var say = function (){
 this.name="zjx";
 this.eat = function(){
   alert("eat");
 }
}

var user1 = {
  say: this.say
}
user1.say();

var user2 = {
 say :this.say
}
user2.say();

alert(user1.say == user2.say);
alert(user1.eat == user2.eat);

输出:
True
False

总结代码如下:
User = function(){
  this.name = "zjx";
  this.say = function(){
   alert("i am " +this.name);
  }
}

var user1 = new User();
user1.say();
这两段代码和下面的三行代码是完全等价的:
var user2 = User.prototype;
user2.constructor();
user2.say();
变相代码:
var user2 = User.prototype;
user2.another = User;
user2.another();
user2.say();

可以说,javascript是基于原型的,每个函数都有对应的原型对象。
1、new操作符就是先赋值于原型对象。
(
A:后台会把构造函数赋给原型对象的某一个属性X,具体名称开需考究。
B:设置constructor属性:当自定义了原型对象比如为{X:x2,Y:x3}时,constructor设置为Object,新增方法、属性或不设置原型对象时指向构造函数。
)
2、然后再把执行原型对象的X方法。
0 0
原创粉丝点击