博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
this作用域、javascript面向…
阅读量:4042 次
发布时间:2019-05-24

本文共 1342 字,大约阅读时间需要 4 分钟。

原文地址:
作者:
此过程模拟了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方法。

转载地址:http://opqdi.baihongyu.com/

你可能感兴趣的文章
Android自定义apk名称、版本号自增
查看>>
adb command not found
查看>>
Xcode 启动页面禁用和显示
查看>>
【剑指offer】q50:树中结点的最近祖先
查看>>
二叉树的非递归遍历
查看>>
【leetcode】Reorder List (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Candy(python)
查看>>
【leetcode】Clone Graph(python)
查看>>
【leetcode】Sum Root to leaf Numbers
查看>>
【leetcode】Pascal's Triangle II (python)
查看>>
java自定义容器排序的两种方法
查看>>
如何成为编程高手
查看>>
本科生的编程水平到底有多高
查看>>
AngularJS2中最基本的文件说明
查看>>
从头开始学习jsp(2)——jsp的基本语法
查看>>
使用与或运算完成两个整数的相加
查看>>
备忘:java中的递归
查看>>
DIV/CSS:一个贴在左上角的标签
查看>>